package com.glela.order.service.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cloopen.rest.sdk.utils.encoder.BASE64Decoder;
import com.glela.activ.service.OActivService;
import com.glela.activ.service.domain.OActivAvlInfoVo;
import com.glela.activ.service.domain.OActivAvlProductVo;
import com.glela.activ.service.domain.OActivAvlVo;
import com.glela.activ.service.domain.OActivProductParam;
import com.glela.activ.service.domain.avl.OActivAvlGiftProductVo;
import com.glela.activ.service.domain.avl.OActivAvlGiftsVo;
import com.glela.api.model.AlipayAppKeyInfo;
import com.glela.api.model.PayAppKeyInfo;
import com.glela.api.pay.util.AlipayConfig;
import com.glela.api.pay.util.PayConfig;
import com.glela.api.pay.yeepay.component.YeePay;
import com.glela.biz.RedPacketBiz;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.ActivityTypeEnum;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.GoodsSelfTypeEnum;
import com.glela.common.constant.GoodsTypeEnum;
import com.glela.common.constant.KeepAccountsTypeConstants;
import com.glela.common.constant.OpenStoreTypeEnum;
import com.glela.common.constant.OrderStatusEnum;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.constant.RoleEnum;
import com.glela.common.constant.StoreTypeEnum;
import com.glela.common.constant.UserJournalStatusEnum;
import com.glela.common.constant.UserMoenyTypeEnum;
import com.glela.common.constant.freightSettlementLimitEnum;
import com.glela.common.exception.PlatformException;
import com.glela.common.model.sms.order.SMSNoticeDelivery;
import com.glela.common.model.sms.order.SMSSuccessOrderPayment;
import com.glela.common.service.SMSService;
import com.glela.common.util.Base64Util;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.NetworkUtil;
import com.glela.common.util.NumberUtil;
import com.glela.common.util.OrderUtil;
import com.glela.common.util.StringUtil;
import com.glela.company.model.CompanyXz;
import com.glela.company.model.vo.CompanyXzVo;
import com.glela.company.service.CompanyService;
import com.glela.company.service.XzOmsLogService;
import com.glela.domain.dto.BackRedPacketRequest;
import com.glela.domain.dto.ConsumeRedPacketRequest;
import com.glela.domain.dto.GiveRedPacketByEventRequest;
import com.glela.goods.mapper.GoodsExtendedAttributeMapper;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.InventoryMapper;
import com.glela.goods.mapper.LimitTimeSaleDetailMapper;
import com.glela.goods.mapper.ProductMapper;
import com.glela.goods.model.Activity;
import com.glela.goods.model.Goods;
import com.glela.goods.model.GoodsCommission;
import com.glela.goods.model.GoodsExtends;
import com.glela.goods.model.Inventory;
import com.glela.goods.model.LimitTimeSaleGoodsCommission;
import com.glela.goods.model.Product;
import com.glela.goods.model.ShareGoods;
import com.glela.goods.model.TalentSerialGood;
import com.glela.goods.model.vo.InventoryVo;
import com.glela.goods.model.vo.StoreVo;
import com.glela.goods.service.ActivityService;
import com.glela.goods.service.BrandService;
import com.glela.goods.service.GoodsService;
import com.glela.live.service.LiveOrderService;
import com.glela.mq.service.OrderQueueService;
import com.glela.order.dao.OrderDao;
import com.glela.order.mapper.AfterSalesMapper;
import com.glela.order.mapper.CommisionMapper;
import com.glela.order.mapper.ExpressCompanyMapper;
import com.glela.order.mapper.OrderDetailMapper;
import com.glela.order.mapper.OrderInfoMapper;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.mapper.OrderPayMapper;
import com.glela.order.mapper.OrderSettlementCommisionMapper;
import com.glela.order.mapper.OrderSettlementMapper;
import com.glela.order.model.AfterSales;
import com.glela.order.model.Commision;
import com.glela.order.model.ExpressCompany;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.OrderSettlement;
import com.glela.order.model.OrderSettlementCommision;
import com.glela.order.model.PayTypeConfig;
import com.glela.order.model.UserCommision;
import com.glela.order.model.UserNormalCommision;
import com.glela.order.model.request.RequestGetOrderObject;
import com.glela.order.model.request.RequestOrderDetail;
import com.glela.order.model.response.HaigouApiAuthentication;
import com.glela.order.model.response.OrderInfoVo;
import com.glela.order.model.response.RespAddOrderInfo;
import com.glela.order.model.response.ResponseGetOrderObject;
import com.glela.order.model.response.ResponseOrderNum;
import com.glela.order.model.response.ResponseShopOrderNum;
import com.glela.order.model.response.order.RespOrderGiftsProductVo;
import com.glela.order.model.vo.order.ErrorMsgGoods;
import com.glela.order.model.vo.order.OrderRecommendAndTeacherVo;
import com.glela.order.model.vo.order.UserRedPacketVo;
import com.glela.order.model.vo.order.UserWalletVo;
import com.glela.order.service.CommissionService;
import com.glela.order.service.OrderObjectService;
import com.glela.order.service.OrderPayService;
import com.glela.order.service.OrderService;
import com.glela.order.service.OrderStatusService;
import com.glela.order.service.impl.vo.OrderActivInfoVo;
import com.glela.order.service.impl.vo.OrderVo;
import com.glela.order.util.StoreComparator;
import com.glela.order.util.UserPromotionComparator;
import com.glela.order.vo.CommisionUpdateStatusVo;
import com.glela.order.vo.OpenStorePriceVo;
import com.glela.order.vo.OrderForThirdResponseXzResult;
import com.glela.order.vo.OrderForXZTeacherVo;
import com.glela.order.vo.OrderSettlementVo;
import com.glela.order.vo.ParamsCommisionVo;
import com.glela.packet.enums.RedPacketBackTypeEnum;
import com.glela.packet.enums.RedPacketEventTypeEnum;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.AppSecretMapper;
import com.glela.platform.mapper.BaseRestrictionsMapper;
import com.glela.platform.mapper.CUserMoneyChangeMapper;
import com.glela.platform.mapper.CUserPointTransactionMapper;
import com.glela.platform.mapper.ChangeProcessLogMapper;
import com.glela.platform.mapper.OperationLogMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserMoneyMapper;
import com.glela.platform.mapper.UserPointJournalMapper;
import com.glela.platform.mapper.UserPromotionMapper;
import com.glela.platform.model.AppSecret;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserMoneyChange;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.ChangeProcessLog;
import com.glela.platform.model.MoneyBusinessType;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.TalentJob;
import com.glela.platform.model.User;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserMoney;
import com.glela.platform.model.UserPayInfo;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.model.UserPromotion;
import com.glela.platform.model.request.ReqHeaderVo;
import com.glela.platform.model.request.RequestPageBaseModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.CUserPointTransactionService;
import com.glela.platform.service.MoneyBusinessTypeService;
import com.glela.platform.service.TalentJobSerice;
import com.glela.platform.service.UserAddressService;
import com.glela.platform.service.UserJournalService;
import com.glela.platform.service.UserMoneyService;
import com.glela.platform.service.UserPayInfoService;
import com.glela.platform.service.UserPointJournalService;
import com.glela.platform.service.UserPromotionService;
import com.glela.platform.service.UserService;
import com.glela.platform.vo.GoodsSimpleVo;
import com.glela.platform.vo.ParamsUserXzbTransactionVo;
import com.glela.platform.vo.UserPromotionVo;
import com.glela.platform.vo.XzbTransactionUpdateVo;
import com.glela.statistics.service.UserEarningsService;
import com.glela.talent.mapper.OrderVipMapper;
import com.glela.talent.model.OrderVip;
import com.glela.talent.service.TalentService;
import com.glela.usermoney.mapper.UserCommisionMapper;

/**
 * @author liujie
 * @2016年10月25日
 */
public abstract class AbstractOrderServiceImpl implements OrderService {
	/** 订单token秒数 */
	private static final int SECONDS_ORDER_TOKEN = 60 * 60 * 1;

	/** 查询用户单次次数 */
	private static final int CALCULATION_NUM = 2;

	private static Logger logger = LoggerFactory.getLogger(AbstractOrderServiceImpl.class);
	public static final String APPID = "小铺来了";
	@Autowired
	protected UserPromotionService		userPromotionService;
	@Autowired
	protected UserJournalMapper			userJournalMapper;
	@Autowired
	protected UserMapper				userMapper;
	@Autowired
	protected LimitTimeSaleDetailMapper	limitTimeSaleDetailMapper;
	@Autowired
	protected UserAddressService		userAddressService;

	@Autowired
	protected UserService			userService;
	@Autowired
	protected UserCommisionMapper	userCommisionMapper;

	@Autowired
	private CUserMoneyChangeMapper		moneyChangeMapper;
	@Autowired
	protected UserPayInfoService		userPayInfoService;
	@Autowired
	private UserPointJournalMapper		userPointJournalMapper;
	@Autowired
	protected OrderDao					orderDao;
	@Autowired
	protected AfterSalesMapper			afterSalesMapper;
	@Autowired
	protected OrderInfoMapper			orderInfoMapper;
	@Autowired
	protected OrderDetailMapper			orderDetailMapper;
	@Autowired
	protected BrandService				brandService;
	@Autowired
	protected CommisionMapper			commisionMapper;
	@Autowired
	private CommissionService			commissionService;
	@Autowired
	protected ChangeProcessLogMapper	LogMapper;
	@Autowired
	protected ExpressCompanyMapper		ExpressCompanyMapper;
	@Autowired
	protected YeePay					yeePay;
	@Autowired
	protected BaseRestrictionsMapper	baseRestrictionsMapper;
	@Autowired
	protected ActivityService			activityService;
	@Autowired
	protected GoodsService				goodsService;
	@Autowired
	protected InventoryMapper			inventoryMapper;

	@Autowired
	protected OrderObjectMapper	orderObjectMapper;
	@Autowired
	private OrderObjectService	orderObjectService;
	@Autowired
	private OrderPayMapper		orderPayMapper;
	@Autowired
	private OrderPayService		orderPayService;

	@Autowired
	protected OActivService oActivService;

	@Autowired
	protected UserMoneyMapper				userMoneyMapper;
	@Autowired
	protected UserMoneyService				userMoneyService;
	@Autowired
	protected CUserMoneyChangeMapper		userMoneyChangeMapper;
	@Autowired
	protected CUserPointTransactionMapper	userPointTransactionMapper;
	@Autowired
	protected UserPointJournalService		userPointJournalService;
	@Autowired
	protected UserJournalService			userJournalService;
	@Autowired
	private UserPromotionMapper				userPromotionMapper;
	@Autowired
	protected CUserPointTransactionService	cUserPointTransactionService;

	@Autowired
	private OrderVipMapper orderVipMapper;

	@Autowired
	private GoodsMapper		goodsMapper;
	@Autowired
	private ProductMapper	productMapper;

	@Autowired
	private TalentService talentService;

	@Autowired
	XzOmsLogService xzOmsLogService;

	@Autowired
	private AppSecretMapper AppSecretMapper;

	@Autowired
	private ExpressCompanyMapper expressCompanyMapper;

	@Autowired
	private OrderStatusService orderStatusService;

	@Autowired
	protected BaseRestrictionsService baseRestrictionsService;

	@Autowired
	protected MoneyBusinessTypeService moneyBusinessTypeService;

	@Autowired
	private TalentJobSerice talentJobSerice;

	@Autowired
	private CompanyService					companyService;
	@Autowired
	private OrderSettlementCommisionMapper	orderSettlementCommisionMapper;
	@Autowired
	protected OrderSettlementMapper			orderSettlementMapper;

	@Autowired
	private OrderQueueService orderQueueService;

	@Autowired
	protected RedisUtil						redisUtil;
	@Autowired
	private UserInfoMapper					userInfoMapper;
	@Autowired
	private UserEarningsService				userEarningsService;
	@Autowired
	private SMSService						smsService;
	@Autowired
	private NotifyWxMsgServiceImpl			notifyWxMsgServiceImpl;
	@Autowired
	private OperationLogMapper				operationLogMapper;
	@Autowired
	private RedPacketBiz					redPacketBiz;
	@Autowired
	private GoodsExtendedAttributeMapper	goodsExtendedAttributeMapper;

	@Autowired
	private LiveOrderService liveOrderService;
	@Override
	public String selectFreightDivideString(OrderSettlement settlement) {
		return null;
	}

	protected String getOrderObjectSn() {
		return CommonConstants.ORDER_OBJECT_PREFIX + OrderUtil.getOrderSn();
	}

	/**
	 * 获取基础配置信息
	 * @return Map<String, BaseRestrictions>
	 */
	public Map<String, BaseRestrictions> selectAllBaseRestrictions() {
		Map<String, BaseRestrictions> baseRestrictionsMap = new HashMap<String, BaseRestrictions>();
		List<BaseRestrictions> list = baseRestrictionsMapper.selectAllBaseRestrictions();
		for (BaseRestrictions baseRestrictions : list) {
			baseRestrictionsMap.put(baseRestrictions.getType(), baseRestrictions);
		}
		return baseRestrictionsMap;
	}

	@Override
	public ResponseResultModel<?> getToOrderInfo(RequestGetOrderObject requestGetOrderObject) {
		return new ResponseResultModel<>(ErrorEnum.C20000, null);
	}

	@Override
	public ResponseResultModel<RespAddOrderInfo> addOrderInfo(RequestOrderDetail requestOrderDetail) throws PlatformException {
		return new ResponseResultModel<>(ErrorEnum.C20000, null);
	}

	/** MaoZeYao **/
	protected Map<String, TalentSerialGood> createTalentSerialGoodMap(List<GoodsSimpleVo> goodsSimpleVoList) {
		//以达人资讯id+商品id为索引，建立达人资讯商品信息集合
		Map<String, TalentSerialGood> talentSerialGoodMap = new HashMap<String, TalentSerialGood>();
		List<TalentSerialGood> talentSerialGoodList = orderDao.selectTalentSerialGoodInId(goodsSimpleVoList);
		for (TalentSerialGood talentSerialGood : talentSerialGoodList) {
			talentSerialGoodMap.put(talentSerialGood.getTalentSerialId() + "_" + talentSerialGood.getGoodId(), talentSerialGood);
		}
		return talentSerialGoodMap;
	}

	/**
	 * 以库存id为索引，建立分享商品集合
	 * @param goodsSimpleVoList
	 * @return Map<Long, ShareGoods>
	 */
	protected Map<Long, ShareGoods> createShareGoodsMap(List<GoodsSimpleVo> goodsSimpleVoList) {
		Map<Long, ShareGoods> shareGoodsMap = new HashMap<Long, ShareGoods>();
		List<ShareGoods> shareGoodsList = orderDao.selectShareGoodsInId(goodsSimpleVoList);
		for (ShareGoods shareGoods : shareGoodsList) {
			shareGoodsMap.put(shareGoods.getId(), shareGoods);
		}
		return shareGoodsMap;
	}

	/**
	 * 计算会员实际售价
	 * @param salePrice 原销售价
	 * @param talentLimit 会员佣金比例
	 * @return int <code>销售价=salePrice * (100 - talentLimit) / 100</code>
	 */
	private int compSalePrice(int salePrice, int talentLimit) {
		return salePrice * (100 - talentLimit) / 100;
	}

	/**
	 * 设置可使用支付类型
	 * @param responseGetOrderObject
	 */
	protected void setPayTypeConfig(ResponseGetOrderObject responseGetOrderObject) {
		responseGetOrderObject.setPayTypeConfigList(new ArrayList<PayTypeConfig>());
	}

	/**
	 * 计算开店销总售价
	 * @param user 当前用户
	 * @param openStoreSelfFee 开店自主商品销售总价
	 * @param totalPrice 商品销售总价
	 * @return OpenStorePriceVo
	 */
	protected OpenStorePriceVo compOpenStorePrice(ResponseUser user, int openStoreSelfFee, int totalPrice) {
		return new OpenStorePriceVo();
	}

	/**
	 * 二次计算商品销售价格
	 * @param oldTotalPrice 原销售总价（未参与开店优惠）
	 * @param totalPrice 当前销售总价
	 * @param openStorePriceVo 开店销售价信息
	 * @param goodsSimpleVoList 购买商品集合
	 */
	protected void compOpenStoreODPrice(int oldTotalPrice, int totalPrice, OpenStorePriceVo openStorePriceVo, List<GoodsSimpleVo> goodsSimpleVoList) {}

	/**
	 * 计算开店价格
	 * @param baseRestrictionsMap 基础配置信息
	 * @param openStoreSelfFee 当前开店B区自营商品总售价
	 * @param orderObject 订单
	 * @return int 开店单优惠折扣比例
	 * @author zls
	 */
	protected int compOpenStorePrice(Map<String, BaseRestrictions> baseRestrictionsMap, int openStoreSelfFee, OrderObject orderObject) {
		return 999999;
	}

	protected void compOpenStoreInfoPrice(int experience, Map<Integer, Integer> openStoreSelfFeeMap, int openStoreSelfFee, OrderObject orderObject, OrderInfo orderInfo) {

	}

	/**
	 * 计算开店单商品销售价（生成交易单时）
	 * @param experience 开店优惠折扣
	 * @param orderObject 交易单
	 * @param orderDetail 订单商品
	 * @param inventoryMap 以库存为索引的订单商品集合
	 * @author zls
	 */
	protected void compOpenStoreDetailPrice(int experience, OrderObject orderObject, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap) {}

	/**
	 * 获取活动信息
	 * @param id 活动id
	 * @return Activity
	 */
	protected Activity selectIngActivity(long id) {
		return activityService.selectIngByPrimaryKey(id);
	}

	/**
	 * 根据活动计算销售价
	 * @param activity 活动
	 * @param salePrice 销售价
	 * @return int 销售价
	 */
	protected int compSalePriceByActivity(Activity activity, int salePrice) {
		if (activity != null) {
			return activity.getSalePrice();
		} else {
			return salePrice;
		}
	}

	@Override
	public ResponseGetOrderObject getOrderObject(RequestGetOrderObject requestGetOrderObject) throws PlatformException {
		DateTime nowTime = new DateTime();
		ResponseUser user = userService.selectUserRoleById(requestGetOrderObject.getUserId());
		ResponseGetOrderObject responseGetOrderObject = new ResponseGetOrderObject();
		List<GoodsSimpleVo> goodsSimpleVoList = orderDao.selectGetOrderGoodsInfo(requestGetOrderObject.getGoodsSimpleVoList());
		int totalPrice = 0;//总销售价
		//用户提交的购买商品信息（以库存id为主键归类）
		Map<Long, GoodsSimpleVo> goodsSimpleVoMap = new HashMap<Long, GoodsSimpleVo>();
		for (GoodsSimpleVo goodsSimpleVo : requestGetOrderObject.getGoodsSimpleVoList()) {
			goodsSimpleVoMap.put(goodsSimpleVo.getInventoryId(), goodsSimpleVo);
		}
		//达人资讯商品,以达人资讯id+商品id为索引，建立大人资讯商品信息集合
		Map<String, TalentSerialGood> talentSerialGoodMap = createTalentSerialGoodMap(requestGetOrderObject.getGoodsSimpleVoList());
		//达人分享商品，以库存id为索引，简历分享商品集合
		Map<Long, ShareGoods> shareGoodsMap = createShareGoodsMap(requestGetOrderObject.getGoodsSimpleVoList());

		//如果活动id大于0并且类型为0 设置活动类型为福利社 (applywelfareid 大于0 活动类型为0归属福利社活动类型，此问题是由于后期增加活动引起，可以认为福利社为特殊类型活动)
		if (requestGetOrderObject.getApplywelfareId() > 0 && requestGetOrderObject.getActivityType() == 0) {
			requestGetOrderObject.setActivityType(ActivityTypeEnum.T2.getCode());
		}
		Activity activity = null;
		//获取非福利社活动
		if (requestGetOrderObject.getApplywelfareId() > 0 && requestGetOrderObject.getActivityType() != ActivityTypeEnum.T2.getCode()) {
			activity = selectIngActivity(requestGetOrderObject.getApplywelfareId());
		}
		int openStoreSelfFee = 0;//开店自主商品应付总金额
		int firstGoodsType = -1;//第一行商品类型 0:c区商品，1:b区商品
		int i = 0;
		ResponseUser talentUser = null;//分享人信息
		long _talentId = 0;
		/*以数据库商品为主封装用户提交商品信息*/
		for (GoodsSimpleVo goodsSimpleVo : goodsSimpleVoList) {
			if (i == 0) {
				firstGoodsType = goodsSimpleVo.getGoodsType();
				_talentId = goodsSimpleVo.getTalentId();
			} else if (goodsSimpleVo.getTalentId() > 0 && goodsSimpleVo.getTalentId() != _talentId) {
				throw new PlatformException(ErrorEnum.C20780, "分享商品每次只能购买同一个分享人的产品");
			}
			//如果商品类型不一致，不允许支付
			if (firstGoodsType != goodsSimpleVo.getGoodsType()) {
				throw new PlatformException(ErrorEnum.C20807, ErrorEnum.C20807.getMessage());
			}
			//商品必须处于可售状态
			if (goodsSimpleVo.getOnlineTime() == null || goodsSimpleVo.getOfflineTime() == null || goodsSimpleVo.getOnlineTime().getTime() - nowTime.getMillis() > 0 || goodsSimpleVo.getOfflineTime().getTime() - nowTime.getMillis() < 0) {
				throw new PlatformException(ErrorEnum.C20401, goodsSimpleVo.getGoodName() + ErrorEnum.C20401.getMessage());
			}
			//封装前端提交的商品信息
			goodsSimpleVo.setQuantity(goodsSimpleVoMap.get(goodsSimpleVo.getInventoryId()).getQuantity());
			goodsSimpleVo.setTalentSerialId(goodsSimpleVoMap.get(goodsSimpleVo.getInventoryId()).getTalentSerialId());
			goodsSimpleVo.setTalentShareGoodId(goodsSimpleVoMap.get(goodsSimpleVo.getInventoryId()).getTalentShareGoodId());
			goodsSimpleVo.setTalentId(goodsSimpleVoMap.get(goodsSimpleVo.getInventoryId()).getTalentId());
			if (i == 0) {
				talentUser = userService.selectUserRoleById(goodsSimpleVo.getTalentId());
			}
			//xz
			//用户角色级别不在达人最小值和讲师级别之间且商品类型为B区商品且商品属于自营商品，累加店铺开店自营商品总金额
			if ((!(user.getLevel() >= CommonConstants.TALENT_MIN_LEVEL && user.getLevel() <= CommonConstants.TALENT_TEACHER_LEVEL)) && goodsSimpleVo.getGoodsType() == GoodsTypeEnum.T1.getCode() && goodsSimpleVo.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
				openStoreSelfFee += (goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			}
			/*商品售价*/
			if (requestGetOrderObject.getApplywelfareId() == 0) {//商品没有归属
				//(用户为会员||(分享者为会员||购买商品为达人期商品||购买商品为达人分享商品))
				if (((talentUser != null && talentUser.getLevel() > CommonConstants.MEMBER_MIN_LEVEL && talentUser.getLevel() <= CommonConstants.MEMBER_MAX_LEVEL) && ((goodsSimpleVo.getTalentSerialId() > 0 && talentSerialGoodMap.get(goodsSimpleVo.getTalentSerialId() + "_" + goodsSimpleVo.getGoodId()) != null) || (goodsSimpleVo.getTalentShareGoodId() > 0 && shareGoodsMap.get(goodsSimpleVo.getTalentShareGoodId()) != null && shareGoodsMap.get(goodsSimpleVo.getTalentShareGoodId()).getGoodId() == goodsSimpleVo.getGoodId()))) || (user.getLevel() > CommonConstants.MEMBER_MIN_LEVEL && user.getLevel() <= CommonConstants.MEMBER_MAX_LEVEL)) {
					goodsSimpleVo.setSalePrice(compSalePrice(goodsSimpleVo.getSalePrice(), goodsSimpleVo.getTalentLimit()));
				}
			} else {
				goodsSimpleVo.setSalePrice(compSalePriceByActivity(activity, goodsSimpleVo.getSalePrice()));
			}
			//商品属于福利社
			if (goodsSimpleVo.getApplywelfareId() == ActivityTypeEnum.T2.getCode()) {
				requestGetOrderObject.setApplywelfareId(goodsSimpleVo.getApplywelfareId());
				requestGetOrderObject.setActivityType(ActivityTypeEnum.T2.getCode());
			} else {
				if (activity == null) {//活动为空置空商品归属
					goodsSimpleVo.setApplywelfareId(0);
					//					goodsSimpleVo.setActivityType(0);
				} else {
					goodsSimpleVo.setApplywelfareId((int) activity.getId());
					goodsSimpleVo.setActivityType(activity.getType());
				}
			}
			// 校验商品是否已享用此次活动
			if (validBuyTheWelare(requestGetOrderObject.getUserId(), requestGetOrderObject.getGoodsSimpleVoList().get(0).getGoodId(), requestGetOrderObject.getApplywelfareId(), requestGetOrderObject.getActivityType())) {
				return null;
			}
			goodsSimpleVo.setUserId(requestGetOrderObject.getUserId());
			totalPrice += goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity();
			i++;
		}

		//计算开店单销售总价
		int oldTotalPrice = totalPrice;
		OpenStorePriceVo openStorePriceVo = compOpenStorePrice(user, openStoreSelfFee, totalPrice);
		//二次计算商品销售价
		totalPrice = openStorePriceVo.getTotalPrice();
		compOpenStoreODPrice(oldTotalPrice, totalPrice, openStorePriceVo, goodsSimpleVoList);

		if (requestGetOrderObject.getApplywelfareId() == 0) {
			if (goodsSimpleVoList.get(0).getGoodsType() == GoodsTypeEnum.T0.getCode()) {//C区商品参与优惠
				List<UserPromotionVo> userPromotionList = userPromotionService.selectUserPromotionByUserIdEx(requestGetOrderObject.getUserId(), goodsSimpleVoList);
				getUserPromotionOrderList(userPromotionList, goodsSimpleVoList);
				responseGetOrderObject.setUserPromotionList(userPromotionList);
			}
			//普通产品的运费
			BaseRestrictions Restrictions = baseRestrictionsService.selectAllBaseRestrictionsByType("order_freight_value");
			if (Restrictions != null && Restrictions.getRestrictions() > totalPrice) {
				responseGetOrderObject.setFreight(Restrictions.getExperience());
			} else {
				responseGetOrderObject.setFreight(Integer.valueOf(Config.getString("orderFreight")));
			}
		} else {
			//活动商品只能购买一个
			if (requestGetOrderObject.getGoodsSimpleVoList() != null && requestGetOrderObject.getGoodsSimpleVoList().size() > 0 && requestGetOrderObject.getGoodsSimpleVoList().get(0).getQuantity() > 1) {
				throw new PlatformException(ErrorEnum.C20780, ErrorEnum.C20780.getMessage());
			}
			//运费
			responseGetOrderObject.setFreight(Integer.parseInt(Config.getString("orderWelfareFreight")));
		}
		if (responseGetOrderObject.getUserPromotionList() == null) {
			responseGetOrderObject.setUserPromotionList(new ArrayList<UserPromotionVo>());
		}
		responseGetOrderObject.setGoodsSimpleVoList(goodsSimpleVoList);
		responseGetOrderObject.setTotalPrice(totalPrice);
		setPayTypeConfig(responseGetOrderObject);
		return responseGetOrderObject;
	}

	/**
	 * 校验购买福利是否已参与，默认活动为福利社。跳过秒杀
	 * @param userId 会员id
	 * @param goodId 商品id
	 * @param applywelfareId 商品归属分类
	 * @param activityType 活动类型
	 * @return boolean true：已参与，false：未享有
	 */
	private boolean validBuyTheWelare(Long userId, Long goodId, Integer applywelfareId, Integer activityType) {
		if (applywelfareId.longValue() > 0 && (activityType == null || activityType == 0)) {
			activityType = ActivityTypeEnum.T2.getCode();
		}
		if (activityType.intValue() == ActivityTypeEnum.T5.getCode()) {
			return false;
		}
		OrderDetail orderDetail = orderDao.selectByUserGoodApplywelfareId(userId, goodId, applywelfareId, activityType);
		if (orderDetail != null) {
			return true;
		} else {
			return false;
		}
	}

	/** 获取可用优惠券 */
	protected List<UserPromotionVo> selcetAvlProm(OrderVo prom) {
		List<UserPromotionVo> userPromotionList = userPromotionService.selectUserPromotion(prom.getUserId(), prom.getBrandIdSet(), prom.getGoodsIdSet());
		List<UserPromotionVo> removeList = new ArrayList<UserPromotionVo>();
		long _max_promotion_fee = 0;
		for (UserPromotionVo userPromotion : userPromotionList) {
			switch (userPromotion.getType()) {
				case 1://现金币
				case 2://通用券
					_max_promotion_fee = prom.getTotalPricePromotion();
					if (userPromotion.getLimited() > prom.getTotalPricePromotion()) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * prom.getTotalPricePromotion() / 100);
						}
					}
					break;
				case 3://品牌券
					long brandTotalAmount = prom.getBrandTotalAmount(userPromotion.getBrandId());
					_max_promotion_fee = brandTotalAmount;
					if (userPromotion.getLimited() > brandTotalAmount) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * brandTotalAmount / 100);
						}
					}
					break;
				case 5://商品券
					long goodsTotalAmount = prom.getGoodsTotalAmount(userPromotion.getGoodId());
					_max_promotion_fee = goodsTotalAmount;
					if (userPromotion.getLimited() > goodsTotalAmount) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * goodsTotalAmount / 100);
						}
					}
					break;
				case 7://自营非自营
					_max_promotion_fee = prom.getTotalPricePromotion();
					if (userPromotion.getLimited() > prom.getTotalPricePromotion()) {
						removeList.add(userPromotion);
					} else if (userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T0.getCode() && prom.isHasNoSelfGoods() || userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T1.getCode() && prom.isHasSelfGoods()) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * prom.getTotalPricePromotion() / 100);
						}
					}
					break;
				default://其它类型不可用
					removeList.add(userPromotion);
			}
			if (userPromotion.getDiscountAmount() > _max_promotion_fee) {//如果优惠金额大于商品销售总额按最大优惠金额封顶
				if (logger.isInfoEnabled()) {
					logger.warn("用户[{}]优惠券【{}】设置错误：优惠金额[{}]大于最大优惠金额[{}]", prom.getUserId(), userPromotion.getId(), userPromotion.getDiscountAmount(), _max_promotion_fee);
				}
				userPromotion.setDiscountAmount(_max_promotion_fee);
				//				removeList.add(userPromotion);
			}
		}
		Collection<UserPromotionVo> existsAll = CollectionUtils.removeAll(userPromotionList, removeList);
		userPromotionList.clear();
		userPromotionList.addAll(existsAll);
		Collections.sort(userPromotionList, new UserPromotionComparator());
		return userPromotionList;
	}

	protected void getUserPromotionOrderList(List<UserPromotionVo> userPromotionList, List<GoodsSimpleVo> goodsList) {
		int totalPrice = 0;
		Map<String, Integer> gbMap = new HashMap<String, Integer>();
		String goodsPrefix = "goods";
		String brandPrefix = "brand";
		String goodsKey = "";
		String brandKey = "";
		for (GoodsSimpleVo goodsSimpleVo : goodsList) {
			goodsKey = goodsPrefix + goodsSimpleVo.getGoodId();
			brandKey = brandPrefix + goodsSimpleVo.getBrandId();
			if (gbMap.get(goodsKey) == null) {
				gbMap.put(goodsKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			} else {
				gbMap.put(goodsKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity() + gbMap.get(goodsKey));
			}
			if (gbMap.get(brandKey) == null) {
				gbMap.put(brandKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			} else {
				gbMap.put(brandKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity() + gbMap.get(brandKey));
			}
			totalPrice += goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity();
		}
		UserPromotionVo userPromotionTemp = null;
		int i = 0;
		List<UserPromotionVo> removeList = new ArrayList<UserPromotionVo>();
		for (UserPromotionVo userPromotion : userPromotionList) {
			switch (userPromotion.getType()) {
				case 1:
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else {
						userPromotion.setDiscountAmount(userPromotion.getAmount());
						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				case 2:
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * totalPrice / 100);
						}
						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				case 3:
					if (gbMap.get(brandPrefix + userPromotion.getBrandId()) == null) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getLimited() > gbMap.get(brandPrefix + userPromotion.getBrandId())) {
							removeList.add(userPromotion);
						} else {
							if (userPromotion.getIsDiscount() == 0) {
								userPromotion.setDiscountAmount(userPromotion.getAmount());
							} else {
								userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * gbMap.get(brandPrefix + userPromotion.getBrandId()) / 100);
							}
							orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
						}
					}
					break;
				case 5:
					if (gbMap.get(goodsPrefix + userPromotion.getGoodId()) == null) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getLimited() > gbMap.get(goodsPrefix + userPromotion.getGoodId())) {
							removeList.add(userPromotion);
						} else {
							if (userPromotion.getIsDiscount() == 0) {
								userPromotion.setDiscountAmount(userPromotion.getAmount());
							} else {
								userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * gbMap.get(goodsPrefix + userPromotion.getGoodId()) / 100);
							}
							orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
						}
					}
					break;
			}
			i++;
		}
		for (UserPromotionVo userPromotion : removeList) {
			userPromotionList.remove(userPromotion);
		}
	}

	/** 优惠金额大的往前挪一位 */
	protected void orderUserPromotionList(int i, UserPromotionVo userPromotionTemp, UserPromotionVo userPromotion, List<UserPromotionVo> userPromotionList) {
		if (i > 0) {
			userPromotionTemp = userPromotionList.get(i - 1);
			if (userPromotion.getDiscountAmount() > userPromotionTemp.getDiscountAmount()) {
				userPromotionList.set(i - 1, userPromotion);
				userPromotionList.set(i, userPromotionTemp);
			}
		}
	}

	/**
	 * 累加销售总价（根据优惠券类型累加销售总价，目前只处理3.品牌券，5.商品券两种类型）
	 * @param bgSalePriceMap 存储按优惠券类型分类统计销售总价集合
	 * @param userPromotion 用户优惠券
	 * @param orderDetail 商品信息
	 * @param inventoryMap 以库存为索引的订单商品集合
	 * @author zls
	 */
	protected void createBGSalePriceMap(Map<Integer, Integer> bgSalePriceMap, UserPromotion userPromotion, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap) {
		switch (userPromotion.getType()) {
			case 3://品牌券
				if (bgSalePriceMap.get(orderDetail.getBrandId()) == null) {
					bgSalePriceMap.put(orderDetail.getBrandId(), inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				} else {
					bgSalePriceMap.put(orderDetail.getBrandId(), bgSalePriceMap.get(orderDetail.getBrandId()) + inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				}
				break;
			case 5://商品券
				if (bgSalePriceMap.get(orderDetail.getGoodId().intValue()) == null) {
					bgSalePriceMap.put(orderDetail.getGoodId().intValue(), inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				} else {
					bgSalePriceMap.put(orderDetail.getGoodId().intValue(), bgSalePriceMap.get(orderDetail.getGoodId().intValue()) + inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				}
				break;
		}
	}

	/**
	 * 累加销售总价（根据优惠券类型累加销售总价，区分店铺，目前只处理3.品牌券，5.商品券两种类型）
	 * @param oinfoBGSalePriceMap 存储按优惠券类型分类统计销售总价集合，区分店铺
	 * @param userPromotion 用户优惠券
	 * @param orderDetail 商品信息
	 * @param inventoryMap 以库存为索引的订单商品集合
	 * @author zls
	 */
	protected void createOInfoBGSalePriceMap(Map<String, Integer> oinfoBGSalePriceMap, UserPromotion userPromotion, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap) {
		switch (userPromotion.getType()) {
			case 3://品牌券
				if (oinfoBGSalePriceMap.get(orderDetail.getStoreId() + "_" + orderDetail.getBrandId()) == null) {
					oinfoBGSalePriceMap.put(orderDetail.getStoreId() + "_" + orderDetail.getBrandId(), inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				} else {
					oinfoBGSalePriceMap.put(orderDetail.getStoreId() + "_" + orderDetail.getBrandId(), oinfoBGSalePriceMap.get(orderDetail.getStoreId() + "_" + orderDetail.getBrandId()) + inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				}
				break;
			case 5://商品券
				if (oinfoBGSalePriceMap.get(orderDetail.getStoreId() + "_" + orderDetail.getGoodId()) == null) {
					oinfoBGSalePriceMap.put(orderDetail.getStoreId() + "_" + orderDetail.getGoodId(), inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				} else {
					oinfoBGSalePriceMap.put(orderDetail.getStoreId() + "_" + orderDetail.getGoodId(), oinfoBGSalePriceMap.get(orderDetail.getStoreId() + "_" + orderDetail.getGoodId()) + inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				}
				break;
		}
	}

	/**
	 * 整单计算优惠券抵扣金额
	 * @param userPromotion 优惠券
	 * @param orderObject 交易单
	 * @param bgSalePriceMap 按品牌及商品统计销售总金额
	 * @return int 优惠抵扣金额
	 * @author zls
	 */
	protected int compOOPomotionDiscount(UserPromotion userPromotion, OrderObject orderObject, Map<Integer, Integer> bgSalePriceMap) throws PlatformException {
		int promotionDiscount = 0;
		if (userPromotion == null) {//没有优惠，返回优惠金额0
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
				promotionDiscount = userPromotion.getAmount();
				break;
			case 2://通用券
			case 7://自主券
				if (userPromotion.getIsDiscount() == 0) {//不是折扣，直接取优惠金额
					promotionDiscount = userPromotion.getAmount();
				} else {//是折扣，计算折扣金额，针对整单
					promotionDiscount = (100 - userPromotion.getDiscount()) * orderObject.getTotalPrice() / 100;
				}
				break;
			case 3://品牌券
				if (userPromotion.getIsDiscount() == 0) {//不是折扣，直接取优惠金额
					promotionDiscount = userPromotion.getAmount();
				} else {//是折扣，按品牌总售价打折
					promotionDiscount = (100 - userPromotion.getDiscount()) * bgSalePriceMap.get(userPromotion.getBrandId()) / 100;
				}
				break;
			case 5://商品券
				if (userPromotion.getIsDiscount() == 0) {//不是折扣，直接取优惠金额
					promotionDiscount = userPromotion.getAmount();
				} else {//是折扣，按商品总销售金额打折
					promotionDiscount = (100 - userPromotion.getDiscount()) * bgSalePriceMap.get(userPromotion.getGoodId()) / 100;
				}
				break;
			default://优惠券不可用
				throw new PlatformException(ErrorEnum.C30110, ErrorEnum.C30110.getDesc());
		}
		return promotionDiscount;
	}

	/**
	 * 按订单占比总销售金额比例分配总优惠抵扣金额（存在精度丢失问题，后续须在代码中处理）
	 * @param userPromotion 优惠券
	 * @param orderObject 交易单
	 * @param orderInfo 订单信息
	 * @param oinfoBGSalePriceMap 按店铺下品牌及商品销售总金额
	 * @param bgSalePriceMap 按品牌及商品分类销售总金额
	 * @return int 优惠抵扣金额
	 * @author zls
	 */
	protected int compOIPomotionDiscount(UserPromotion userPromotion, OrderObject orderObject, OrderInfo orderInfo, Map<String, Integer> oinfoBGSalePriceMap, Map<Integer, Integer> bgSalePriceMap) throws PlatformException {
		int promotionDiscount = 0;
		if (userPromotion == null) {//优惠券不存在，默认优惠抵扣为0
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
				promotionDiscount = ((Double) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * userPromotion.getAmount())).intValue();
				break;
			case 2://通用券
				if (userPromotion.getIsDiscount() == 0) {
					promotionDiscount = ((Double) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * userPromotion.getAmount())).intValue();
				} else {
					promotionDiscount = ((Double) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * (100 - userPromotion.getDiscount()) * orderObject.getTotalPrice() / 100)).intValue();
				}
				break;
			case 3://品牌券
				if (oinfoBGSalePriceMap.get(orderInfo.getStoreId() + "_" + userPromotion.getBrandId()) == null) {
					orderInfo.setPromotionId(0);
					promotionDiscount = -1;
				} else {
					if (userPromotion.getIsDiscount() == 0) {
						promotionDiscount = ((Double) (oinfoBGSalePriceMap.get(orderInfo.getStoreId() + "_" + userPromotion.getBrandId()).doubleValue() / bgSalePriceMap.get(userPromotion.getBrandId()) * userPromotion.getAmount())).intValue();
					} else {
						promotionDiscount = ((Double) (oinfoBGSalePriceMap.get(orderInfo.getStoreId() + "_" + userPromotion.getBrandId()).doubleValue() / bgSalePriceMap.get(userPromotion.getBrandId()) * (100 - userPromotion.getDiscount()) * bgSalePriceMap.get(userPromotion.getBrandId()) / 100)).intValue();
					}
				}
				break;
			case 5://商品券
				if (oinfoBGSalePriceMap.get(orderInfo.getStoreId() + "_" + userPromotion.getGoodId()) == null) {
					orderInfo.setPromotionId(0);
					promotionDiscount = -1;
				} else {
					if (userPromotion.getIsDiscount() == 0) {
						promotionDiscount = ((Double) (oinfoBGSalePriceMap.get(orderInfo.getStoreId() + "_" + userPromotion.getGoodId()).doubleValue() / bgSalePriceMap.get(userPromotion.getGoodId()) * userPromotion.getAmount())).intValue();
					} else {
						promotionDiscount = ((Double) (oinfoBGSalePriceMap.get(orderInfo.getStoreId() + "_" + userPromotion.getGoodId()).doubleValue() / bgSalePriceMap.get(userPromotion.getGoodId()) * (100 - userPromotion.getDiscount()) * bgSalePriceMap.get(userPromotion.getGoodId()) / 100)).intValue();
					}
				}
				break;
		}
		return promotionDiscount;
	}

	/**
	 * <dl>
	 * <dt>计算商品优惠抵扣金额</dt>
	 * <dd>根据优惠类型分摊总优惠抵扣金额（分摊比例为商品应付金额/交易应付总金额）</dd>
	 * <dd>注：有精度缺失问题</dd>
	 * </dl>
	 * @param userPromotion 优惠信息
	 * @param orderObject 交易单
	 * @param orderDetail 商品明细
	 * @param bgSalePriceMap 品牌、商品id为分类的商品销售总价
	 * @return int 优惠抵扣金额
	 * @author zls
	 * @date 2017年6月12日 下午3:51:19
	 */
	protected int compODPomotionDiscount(UserPromotion userPromotion, OrderObject orderObject, OrderDetail orderDetail, Map<Integer, Integer> bgSalePriceMap) {
		int promotionDiscount = 0;
		if (userPromotion == null) {
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
				promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * userPromotion.getAmount())).intValue();
				break;
			case 2://通用券
				if (userPromotion.getIsDiscount() == 0) {
					promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * userPromotion.getAmount())).intValue();
				} else {
					promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * (100 - userPromotion.getDiscount()) * orderObject.getTotalPrice() / 100)).intValue();
				}
				break;
			case 3://品牌券
				if (orderDetail.getBrandId().intValue() != userPromotion.getBrandId()) {
					promotionDiscount = -1;
				} else {
					if (userPromotion.getIsDiscount() == 0) {
						promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / bgSalePriceMap.get(userPromotion.getBrandId()) * userPromotion.getAmount())).intValue();
					} else {
						promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / bgSalePriceMap.get(userPromotion.getBrandId()) * (100 - userPromotion.getDiscount()) * bgSalePriceMap.get(userPromotion.getBrandId()) / 100)).intValue();
					}
				}
				break;
			case 5://商品券
				if (orderDetail.getGoodId().intValue() != userPromotion.getGoodId()) {
					promotionDiscount = -1;
				} else {
					if (userPromotion.getIsDiscount() == 0) {
						promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / bgSalePriceMap.get(userPromotion.getGoodId()) * userPromotion.getAmount())).intValue();
					} else {
						promotionDiscount = ((Double) (orderDetail.getTotalPrice().doubleValue() / bgSalePriceMap.get(userPromotion.getGoodId()) * (100 - userPromotion.getDiscount()) * bgSalePriceMap.get(userPromotion.getGoodId()) / 100)).intValue();
					}
				}
				break;
		}
		return promotionDiscount;
	}

	/**
	 * 设置交易店中店用户id
	 * @param requestOrderDetail 用户提交交易订单信息
	 * @param user 当前用户
	 * @param orderObject 交易单
	 * @author zls
	 */
	protected void setOpenStoreUser(RequestOrderDetail requestOrderDetail, ResponseUser user, OrderObject orderObject) {}

	/**
	 * 验证活动是否存在
	 * @param activity 活动
	 * @return boolean true：存在，false：不存在
	 */
	protected boolean validActivity(Activity activity) {
		if (activity == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 扣减库存：参与活动商品扣减活动库存，不参与活动的普通商品扣减一般库存
	 * @param orderDetail 商品信息
	 * @param activity 活动
	 * @param size 数量
	 * @param inventoryMap 以库存id为索引的商品集合
	 * @throws PlatformException 如果扣减库存失败，抛出无库存
	 * @author zls
	 */
	protected void updateCheckInventory(OrderDetail orderDetail, Activity activity, int size, Map<Long, InventoryVo> inventoryMap) throws PlatformException {
		if (activity != null) {
			int inResult = activityService.subInventoryNumById(activity.getId(), orderDetail.getQuantity(), orderDetail.getInventoryId());
			if (inResult < 1) {
				throw new PlatformException(ErrorEnum.C20409, orderDetail.getGoodName() + "(" + orderDetail.getInventoryId() + ")" + orderDetail.getSpecName() + ErrorEnum.C20409.getMessage());
			}
		} else {
			int inResult = orderDao.subInventoryNumById(orderDetail.getInventoryId(), orderDetail.getQuantity());
			if (inResult != 1) {
				throw new PlatformException(ErrorEnum.C20409, orderDetail.getGoodName() + "(" + orderDetail.getInventoryId() + ")" + orderDetail.getSpecName() + ErrorEnum.C20409.getMessage());
			}
		}
	}

	@Override
	public String addOrderObject(RequestOrderDetail requestOrderDetail) throws PlatformException {
		String result = "error";
		try {
			if ((CollectionUtils.isEmpty(requestOrderDetail.getOrderDetailList()) || requestOrderDetail.getDeliveryWay() == null || requestOrderDetail.getPayType() == null) || (requestOrderDetail.getDeliveryWay() != 2 && requestOrderDetail.getMemberDeliveryAddressId() == null)) {
				throw new PlatformException(ErrorEnum.C20102, ErrorEnum.C20102.getMessage());
			}

			List<OrderDetail> orderDetailList = requestOrderDetail.getOrderDetailList();
			//如果商品归属分类 （1.正常2.福利社 3体验）为空，默认为0
			if (orderDetailList.get(0).getApplywelfareId() == null) {
				orderDetailList.get(0).setApplywelfareId(0);
			}
			Map<Long, InventoryVo> inventoryMap = new HashMap<Long, InventoryVo>();
			createInventoryMap(inventoryMap, orderDetailList);
			// int inResult = orderDao.batchSubInventoryNumById(orderDetailList);
			// if (inResult<1) {
			// 	throw new PlatformException(ErrorEnum.C20409,ErrorEnum.C20409.getMessage());
			// }
			ResponseUser user = userService.selectUserRoleById(orderDetailList.get(0).getUserId());
			List<GoodsSimpleVo> goodsSimpleVoList = new ArrayList<GoodsSimpleVo>();//订单简单商品信息集合
			int firstGoodsType = -1;//第一行商品类型 0:c区商品，1:b区商品 |用于判断b、c区商品不能够一同支付
			int i0 = 0;
			int openStoreSelfFee = 0;//B区自有商品总售价
			Map<Integer, Integer> openStoreSelfFeeMap = new HashMap<Integer, Integer>();//B区店铺自有商品应付总金额,
			long _talenId = 0;
			long nowTimeMillis = System.currentTimeMillis();
			for (OrderDetail orderDetail : orderDetailList) {
				/*校验*/
				//1：b、c区商品不能一同支付
				if (i0 == 0) {
					firstGoodsType = orderDetail.getGoodsType();
					_talenId = orderDetail.getTalentId() == null ? 0 : orderDetail.getTalentId();
				} else {
					if (orderDetail.getTalentId() != null && orderDetail.getTalentId().longValue() > 0 && orderDetail.getTalentId().longValue() != _talenId) {
						throw new PlatformException(ErrorEnum.C20780, "分享商品每次只能购买同一个分享人的产品");
					}
				}
				if (firstGoodsType != orderDetail.getGoodsType()) {
					throw new PlatformException(ErrorEnum.C20807, ErrorEnum.C20807.getMessage());
				}
				//2：下单商品必须上架可售
				if (inventoryMap.get(orderDetail.getInventoryId()) == null || inventoryMap.get(orderDetail.getInventoryId()).isNotOnTheShelf(nowTimeMillis)) {
					throw new PlatformException(ErrorEnum.C20401, orderDetail.getGoodName() + ErrorEnum.C20401.getMessage());
				}

				//商品分类属于活动类型福利社，设置下单商品分类及活动类型为福利社
				if (inventoryMap.get(orderDetail.getInventoryId()).getApplywelfareId() == ActivityTypeEnum.T2.getCode()) {
					orderDetail.setApplywelfareId(inventoryMap.get(orderDetail.getInventoryId()).getApplywelfareId());
					orderDetail.setActivityType(ActivityTypeEnum.T2.getCode());
				}

				//封装分享商品信息
				GoodsSimpleVo goodsSimpleVo = new GoodsSimpleVo();
				goodsSimpleVo.setTalentSerialId(orderDetail.getTalentSerialId());
				goodsSimpleVo.setTalentShareGoodId(orderDetail.getTalentShareGoodId());
				goodsSimpleVoList.add(goodsSimpleVo);

				//xz
				// 用户级别不在达人最小等级和讲师等级之间且商品类型为B区且商品属自营
				if ((!(user.getLevel() >= CommonConstants.TALENT_MIN_LEVEL && user.getLevel() <= CommonConstants.TALENT_TEACHER_LEVEL)) && orderDetail.getGoodsType() == GoodsTypeEnum.T1.getCode() && inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
					openStoreSelfFee += inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity();
					if (openStoreSelfFeeMap.get(orderDetail.getStoreId()) == null) {
						openStoreSelfFeeMap.put(orderDetail.getStoreId(), inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
					} else {
						openStoreSelfFeeMap.put(orderDetail.getStoreId(), openStoreSelfFeeMap.get(orderDetail.getStoreId()) + inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
					}
				}
				i0++;
			}
			/*活动*/
			Activity activity = null;
			if (orderDetailList.get(0).getApplywelfareId().intValue() != 0) {
				//商品活动类型不属于福利社
				if (orderDetailList.get(0).getActivityType() != null && orderDetailList.get(0).getActivityType().intValue() != ActivityTypeEnum.T2.getCode()) {
					activity = selectIngActivity(orderDetailList.get(0).getApplywelfareId());
					if (!validActivity(activity)) {
						return "noActivity";
					}
				}
				//校验是否已享有此活动福利
				if (validBuyTheWelare(orderDetailList.get(0).getUserId(), orderDetailList.get(0).getGoodId(), orderDetailList.get(0).getApplywelfareId(), orderDetailList.get(0).getActivityType())) {
					return null;
				}
			}
			Map<String, TalentSerialGood> talentSerialGoodMap = createTalentSerialGoodMap(goodsSimpleVoList);
			Map<Long, ShareGoods> shareGoodsMap = createShareGoodsMap(goodsSimpleVoList);

			/*生成交易单*/
			//生成交易单号
			StringBuffer orderSn = new StringBuffer();
			orderSn.append(CommonConstants.ORDER_OBJECT_PREFIX).append(OrderUtil.getOrderSn());
			OrderObject orderObject = new OrderObject();
			orderObject.setOrderSn(orderSn.toString());
			result = orderObject.getOrderSn();

			UserPromotion userPromotion = null;
			if (orderDetailList.get(0).getApplywelfareId().intValue() != 0) {//参与活动的商品订单只允许支付一次，且不允许使用现金币及优惠
				if (orderDetailList.get(0).getQuantity().intValue() > 1) {
					throw new PlatformException(ErrorEnum.C20780, ErrorEnum.C20780.getMessage());
				}
				requestOrderDetail.setCashCoin(0);
				requestOrderDetail.setPromotionId(0);
			} else {//普通订单，未参与活动
				//用户现金币不能超额支付
				if (user.getMoney().longValue() < requestOrderDetail.getCashCoin()) {
					requestOrderDetail.setCashCoin(user.getMoney().intValue());
				}
				//扣除用户本次现金币
				int umResult = userService.updateSubMoneyById(user.getUserId(), requestOrderDetail.getCashCoin());
				if (umResult == 0) {//本次现金币支付不可用，设置现金币花费为0
					if (umResult == 0) {
						logger.error("订单号" + orderObject.getOrderSn() + ":用户" + orderDetailList.get(0).getUserId() + "的现金币" + requestOrderDetail.getCashCoin() + "不够用，目前只有" + user.getMoney());
						requestOrderDetail.setCashCoin(0);
					}
				} else {
					//开始记录日志
					ChangeProcessLog Log = new ChangeProcessLog();
					Log.setDescription("妆币抵扣现金[生成订单]");
					Log.setMethod("AbstractOrderServiceImpl.addOrderObject");
					Log.setPrimaryID(String.valueOf(user.getUserId()));
					Log.setTableName("yg_user.c_user");
					Log.getBeforeMap().put("Money", user.getMoney());
					Log.getAfterMap().put("Money", user.getMoney() - requestOrderDetail.getCashCoin());
					LogMapper.insert(Log);
				}
				if (requestOrderDetail.getPromotionId() > 0) {//使用优惠券
					// 查找前端提交优惠券信息，但未对此优惠券有效性进行验证
					userPromotion = userPromotionService.selectUserPromotionByPromotionDetailIdAndUserId(requestOrderDetail.getPromotionId(), orderDetailList.get(0).getUserId());
					int upResult = userPromotionService.updateSubUserPromotionNumber(requestOrderDetail.getPromotionId(), orderDetailList.get(0).getUserId());
					if (upResult == 0) {// 优惠券未使用，没有将优惠券置空，后续代码又根据此优惠券进行处理
						logger.error("订单号" + orderObject.getOrderSn() + ":用户" + orderDetailList.get(0).getUserId() + "的优惠券" + requestOrderDetail.getPromotionId() + "不可用");
						requestOrderDetail.setPromotionId(0);
					}
				}
			}
			//用户配送地址
			UserAddress userAddress = userAddressService.selectUserAddressById(requestOrderDetail.getMemberDeliveryAddressId());
			//根据订单商品店铺id排序
			Collections.sort(requestOrderDetail.getOrderDetailList(), new StoreComparator());
			List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>();
			int i = 0;
			int storeId = 0;
			StoreVo storeVo = null;
			int totalPrice = 0;//总销售金额
			int totalSettlementPrice = 0;//总结算金额
			Map<Integer, Integer> bgSalePriceMap = new HashMap<Integer, Integer>();//按品牌及商品分类统计销售总金额
			Map<Integer, Integer> oiTotalPriceMap = new HashMap<Integer, Integer>();//店铺实际总销售金额
			Map<Integer, Integer> oiTotalSettlementPriceMap = new HashMap<Integer, Integer>();//店铺实际总结算金额
			Map<String, Integer> oinfoBGSalePriceMap = new HashMap<String, Integer>();

			//获取达人
			ResponseUser talentUser = null;
			if (requestOrderDetail.getOrderDetailList().get(0).getTalentId() != null && requestOrderDetail.getOrderDetailList().get(0).getTalentId().longValue() > 0) {
				talentUser = userService.selectUserRoleById(requestOrderDetail.getOrderDetailList().get(0).getTalentId());
			}
			//获取开店订单优惠比例且标注此单是否为开店单
			Map<String, BaseRestrictions> baseRestrictionsMap = selectAllBaseRestrictions();
			int experience = compOpenStorePrice(baseRestrictionsMap, openStoreSelfFee, orderObject);

			for (OrderDetail orderDetail : requestOrderDetail.getOrderDetailList()) {
				updateCheckInventory(orderDetail, activity, 1, inventoryMap);
				if (i == 0) {//生成交易单
					createOrderObject(orderObject, orderDetail, requestOrderDetail, userAddress);
				}
				//店铺id不同，生成新的订单
				if (orderDetail.getStoreId().intValue() != storeId) {
					storeVo = brandService.getStoreById(orderDetail.getStoreId().intValue());
					OrderInfo orderInfo = new OrderInfo();
					createOrderInfo(orderInfo, orderDetail, requestOrderDetail, storeVo, userAddress);
					orderInfoList.add(orderInfo);
				}
				//开店单计算开店优惠
				compOpenStoreDetailPrice(experience, orderObject, orderDetail, inventoryMap);
				//商品实际售价，不参与活动的享受会员价，参与活动的以活动价为主，两种不能同时参与
				if (orderDetail.getApplywelfareId() == null || orderDetail.getApplywelfareId().intValue() == 0) {//没有活动（普通订单）
					//当前用户为会员&&(分享达人是会员&&(此商品是达人期资讯商品或分享商品))
					if (((talentUser != null && talentUser.getLevel() > CommonConstants.MEMBER_MIN_LEVEL && talentUser.getLevel() <= CommonConstants.MEMBER_MAX_LEVEL) && ((orderDetail.getTalentSerialId().intValue() > 0 && talentSerialGoodMap.get(orderDetail.getTalentSerialId() + "_" + orderDetail.getGoodId()) != null) || (orderDetail.getTalentShareGoodId().longValue() > 0 && shareGoodsMap.get(orderDetail.getTalentShareGoodId()) != null && shareGoodsMap.get(orderDetail.getTalentShareGoodId()).getGoodId() == orderDetail.getGoodId().longValue()))) || (user.getLevel() > CommonConstants.MEMBER_MIN_LEVEL && user.getLevel() <= CommonConstants.MEMBER_MAX_LEVEL)) {
						inventoryMap.get(orderDetail.getInventoryId()).setSalePrice(compSalePrice(inventoryMap.get(orderDetail.getInventoryId()).getSalePrice(), inventoryMap.get(orderDetail.getInventoryId()).getTalentLimit()));
					}
				} else {
					inventoryMap.get(orderDetail.getInventoryId()).setSalePrice(compSalePriceByActivity(activity, inventoryMap.get(orderDetail.getInventoryId()).getSalePrice()));
				}
				//				if (!((orderDetail.getTalentSerialId().intValue() > 0 && talentSerialGoodMap
				//						.get(orderDetail.getTalentSerialId() + "_" + orderDetail.getGoodId()) != null)
				//						|| (orderDetail.getTalentShareGoodId().longValue() > 0
				//								&& shareGoodsMap.get(orderDetail.getTalentShareGoodId()) != null
				//								&& shareGoodsMap.get(orderDetail.getTalentShareGoodId()).getGoodId() == orderDetail
				//										.getGoodId().longValue()))) {
				//					orderDetail.setTalentId(0L);
				//				}

				//累加店铺总销售金额
				if (oiTotalPriceMap.get(orderDetail.getStoreId()) == null) {
					oiTotalPriceMap.put(orderDetail.getStoreId(), inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				} else {
					oiTotalPriceMap.put(orderDetail.getStoreId(), oiTotalPriceMap.get(orderDetail.getStoreId()) + inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity());
				}
				//累加店铺总结算金额
				if (oiTotalSettlementPriceMap.get(orderDetail.getStoreId()) == null) {
					oiTotalSettlementPriceMap.put(orderDetail.getStoreId(), inventoryMap.get(orderDetail.getInventoryId()).getSettlementPrice() * orderDetail.getQuantity());
				} else {
					oiTotalSettlementPriceMap.put(orderDetail.getStoreId(), oiTotalSettlementPriceMap.get(orderDetail.getStoreId()) + inventoryMap.get(orderDetail.getInventoryId()).getSettlementPrice() * orderDetail.getQuantity());
				}
				//累加总销售金额
				totalPrice += inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * orderDetail.getQuantity();
				//累加总结算金额
				totalSettlementPrice += inventoryMap.get(orderDetail.getInventoryId()).getSettlementPrice() * orderDetail.getQuantity();
				//用户使用了优惠券
				if (requestOrderDetail.getPromotionId() != 0 && userPromotion != null) {
					createBGSalePriceMap(bgSalePriceMap, userPromotion, orderDetail, inventoryMap);
					createOInfoBGSalePriceMap(oinfoBGSalePriceMap, userPromotion, orderDetail, inventoryMap);
				}
				//xz old
				//设置校验店铺id为当前店铺id
				storeId = orderDetail.getStoreId();
				i++;
			}
			//设置总销售金额
			orderObject.setTotalPrice(totalPrice);
			//			Map<String,BaseRestrictions> baseRestrictionsMap=selectAllBaseRestrictions();
			//			int experience=compOpenStorePrice(baseRestrictionsMap,openStoreSelfFee, orderObject);
			//设置总结算金额
			orderObject.setTotalSettlementPrice(totalSettlementPrice);
			//计算整单优惠券抵扣金额
			int promotionDiscount = compOOPomotionDiscount(userPromotion, orderObject, bgSalePriceMap);
			orderObject.setPromotionDiscount(promotionDiscount);
			//设置运费
			if (orderDetailList.get(0).getApplywelfareId().intValue() != 0) {//福利社产品的运费
				orderObject.setFreight(Integer.valueOf(Config.getString("orderWelfareFreight")));
				orderInfoList.get(0).setFreight(Integer.valueOf(Config.getString("orderWelfareFreight")));
			} else {//普通产品的运费
				BaseRestrictions Restrictions = baseRestrictionsService.selectAllBaseRestrictionsByType("order_freight_value");
				if (Restrictions != null && Restrictions.getRestrictions() > orderObject.getTotalPrice().intValue()) {
					orderObject.setFreight(Restrictions.getExperience());
				} else {
					orderObject.setFreight(Integer.valueOf(Config.getString("orderFreight")));
				}
				//				orderObject.setFreight(Integer.valueOf(Config.getString("orderFreight")));
			}
			orderObject.setTotalFee(orderObject.getTotalPrice() + orderObject.getFreight() - orderObject.getPromotionDiscount() - orderObject.getCashCoin());
			// 如果实付总金额小于等于0，默认付邮费
			if (orderObject.getTotalFee().intValue() <= 0) {
				orderObject.setTotalFee(orderObject.getFreight());
			}
			// orderObject.setCommisionFee(commisionFee);
			//设置交易订单店中店用户id
			setOpenStoreUser(requestOrderDetail, user, orderObject);
			//生成交易订单
			int ooResult = orderDao.insertOrderObjectSelective(orderObject);
			if (ooResult != 1) {
				throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
			}

			/*设置订单信息*/
			Map<Integer, Long> orderInfoStoreIdMap = new HashMap<Integer, Long>();//以店铺为索引的订单主键集合
			Map<Long, OrderInfo> orderInfoIdMap = new HashMap<Long, OrderInfo>();//以订单主键为索引的订单信息集合
			//			int oiAllTotalFee = 0;//所有订单应付金额累计和
			int ii = 0;
			int oiPreTotalCashCoin = 0;//所有订单现金币累计和
			int oiPreTotalPomotionDiscount = 0;//所有订单优惠抵扣累计和
			int oiLastPomotionDiscount = 0;//最后一笔订单优惠抵扣金额
			int oiLastPomotionDiscountII = 0;//最后一笔订单下标
			int oiPreFreight = 0;//所有订单运费累计和
			for (OrderInfo orderInfo : orderInfoList) {
				if (orderInfo.getFreight() == null) {//运费为空，置为0
					orderInfo.setFreight(0);
				}
				orderInfo.setTotalPrice(oiTotalPriceMap.get(orderInfo.getStoreId()));
				//				compOpenStoreInfoPrice(experience,openStoreSelfFeeMap,openStoreSelfFee,orderObject,orderInfo);
				//按店铺销售总金额占比，分摊总运费（丢失的精度放到最后一单运费）
				orderInfo.setFreight((int) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * orderObject.getFreight()));
				if (ii == orderInfoList.size() - 1) {
					orderInfo.setFreight(orderObject.getFreight() - oiPreFreight);
				}

				//订单结算金额
				orderInfo.setTotalSettlementPrice(oiTotalSettlementPriceMap.get(orderInfo.getStoreId()));

				//按店铺销售总金额占比总销售金额比例，分摊现金币（丢失精度放到最后一单现金币）
				int cashCoin = ((Double) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * orderObject.getCashCoin())).intValue();
				if (ii == orderInfoList.size() - 1) {
					cashCoin = orderObject.getCashCoin() - oiPreTotalCashCoin;
				}
				orderInfo.setCashCoin(cashCoin);

				//订单优惠
				orderInfo.setPromotionId(orderObject.getPromotionId());
				int oinfoPromotionDiscount = compOIPomotionDiscount(userPromotion, orderObject, orderInfo, oinfoBGSalePriceMap, bgSalePriceMap);
				if (oinfoPromotionDiscount == -1) {//没有分摊到总优惠调整金额
					oinfoPromotionDiscount = 0;
				} else {
					oiLastPomotionDiscount = oinfoPromotionDiscount;
					oiLastPomotionDiscountII = ii;
				}
				orderInfo.setPromotionDiscount(oinfoPromotionDiscount);

				//订单实付金额
				int totalFee = orderInfo.getTotalPrice() + orderInfo.getFreight() - orderInfo.getPromotionDiscount() - orderInfo.getCashCoin();
				if (totalFee <= 0) {//实付金额小于等于0，设置应付金额为运费
					totalFee = orderInfo.getFreight();
				}
				/*if ((oiAllTotalFee + totalFee) >= orderObject.getTotalFee() - orderObject.getFreight()) {
					totalFee = orderObject.getTotalFee() - orderObject.getFreight() - oiAllTotalFee;
				}*/
				orderInfo.setTotalFee(totalFee);

				orderInfo.setCommisionFee(0);//分佣金额
				orderInfo.setOrderObjectId(orderObject.getId());
				//				int oiResult = orderDao.insertOrderInfoSelective(orderInfo);
				//				if (oiResult != 1) {
				//					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				//				}
				//				orderInfoStoreIdMap.put(orderInfo.getStoreId(), orderInfo.getId());
				//				orderInfoIdMap.put(orderInfo.getId(), orderInfo);
				//				oiAllTotalFee += totalFee;
				oiPreTotalCashCoin += orderInfo.getCashCoin();
				oiPreTotalPomotionDiscount += orderInfo.getPromotionDiscount();
				oiPreFreight += orderInfo.getFreight();
				ii++;
			}
			//计算最后一笔订单优惠抵扣金额（处理上面按比例分摊时的精度缺失问题，把缺失的部分放到最后一笔订单上）
			orderInfoList.get(oiLastPomotionDiscountII).setPromotionDiscount(orderObject.getPromotionDiscount() - (oiPreTotalPomotionDiscount - oiLastPomotionDiscount));
			//重新计算实付金额
			int infoTotalFee = orderInfoList.get(oiLastPomotionDiscountII).getTotalPrice() + orderInfoList.get(oiLastPomotionDiscountII).getFreight() - orderInfoList.get(oiLastPomotionDiscountII).getPromotionDiscount() - orderInfoList.get(oiLastPomotionDiscountII).getCashCoin();
			orderInfoList.get(oiLastPomotionDiscountII).setTotalFee(infoTotalFee);

			//计算总额
			infoTotalFee = 0;
			for (OrderInfo o : orderInfoList) {
				infoTotalFee += o.getTotalFee();
			}
			//子单支付金额总和和父单不一致
			if (infoTotalFee != orderObject.getTotalFee()) {
				//开始记录日志
				ChangeProcessLog Log = new ChangeProcessLog();
				Log.setMethod("AbstractOrderServiceImpl.addOrderObject");
				Log.setPrimaryID("");
				Log.setDescription(ErrorEnum.C20288.getMessage());
				Log.setTableName("yg_order.order");
				Log.getBeforeMap().put("order", JSON.toJSONString(orderInfoList));
				LogMapper.insert(Log);
				//throw new PlatformException(ErrorEnum.C20288, ErrorEnum.C20288.getMessage());
			}

			//把订单存数到数据库
			for (OrderInfo orderInfo : orderInfoList) {
				int oiResult = orderDao.insertOrderInfoSelective(orderInfo);
				if (oiResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
				//整理订单相关索引数据，用于下面生成订单商品明细
				orderInfoStoreIdMap.put(orderInfo.getStoreId(), orderInfo.getId());
				orderInfoIdMap.put(orderInfo.getId(), orderInfo);
			}
			// int oiResult = orderDao.batchInsertOrderInfo(orderInfoList);
			// if (oiResult < orderInfoList.size()) {
			// throw new PlatformException(ErrorEnum.C20000,
			// ErrorEnum.C20000.getMessage());
			// }

			/*生成订单商品明细*/
			Map<Long, Integer> odAllTotalFeeMap = new HashMap<Long, Integer>();//按订单分类，累加商品应付金额
			Map<Long, Integer> odAllCashCoinMap = new HashMap<Long, Integer>();
			Map<Long, Integer> odAllPomotionDiscountMap = new HashMap<Long, Integer>();
			Map<Long, int[]> odLastPomotionDiscountMap = new HashMap<Long, int[]>();//订单最后一个商品优惠抵扣金额（用于处理精度缺失问题）
			//推荐人身份及达人身份，以商品达人为准，如果不存在默认取当前登录人
			/*String recommendFrom = user.getRecommendFrom();//推荐人身份ID
			String talentTeacher = user.getTalentTeacher();//达人导师/经纪人身份id
			Long talentId = requestOrderDetail.getOrderDetailList().get(0).getTalentId();
			if (talentId != null && talentId > 0) {
				UserInfo talentUserInfo = userService.selectUserInfoByUserId(talentId);
				if (talentUser != null) {
					recommendFrom = talentUserInfo.getPersionId();
					talentTeacher = talentUser.getTalentTeacher();
				} else {
					recommendFrom = "";
					talentTeacher = "";
				}
			}*/

			// 2017-7-3修改
			Long talentId = requestOrderDetail.getOrderDetailList().get(0).getTalentId();

			String recommendFrom = BaseConstants.XZ_SISTER_PERSION_ID;//推荐人身份ID
			String talentTeacher = "";//达人导师/经纪人身份id

			if (talentId != null && talentId > 0) {
				UserInfo sellUserInfo = userService.selectUserInfoByUserId(talentId);
				recommendFrom = sellUserInfo.getPersionId();
				talentTeacher = talentUser.getTalentTeacher();
			} else {
				if (user.getRecommendFrom() != null && !"".equals(user.getRecommendFrom())) {
					recommendFrom = user.getRecommendFrom();
					talentTeacher = user.getTalentTeacher();
				}
			}
			//这里做一步验证 验证推荐人和讲师
			if (!"".equals(recommendFrom)) {//推荐人不为空
				ResponseUser u = userService.selectUserRoleByPersonId(recommendFrom);
				if (u != null && u.getRoleId() > 2 && u.getRoleId() < 7) {//店主
					talentTeacher = u.getTalentTeacher();
				}
			}
			//			CompOpenStoreDetailVo compOpenStoreDetailVo = new CompOpenStoreDetailVo();
			//封装订单商品明细
			for (int j = 0; j < requestOrderDetail.getOrderDetailList().size(); j++) {
				OrderDetail orderDetail = requestOrderDetail.getOrderDetailList().get(j);
				orderDetail.setRecommendFrom(recommendFrom);//普通推荐人身份id
				orderDetail.setMemberRecommend(user.getMemberRecommend());//会员推荐人
				orderDetail.setTalentTeacher(talentTeacher);//达人导师/经纪人身份id
				orderDetail.setOrderId(orderInfoStoreIdMap.get(orderDetail.getStoreId()));
				orderDetail.setOrderObjectId(orderObject.getId());
				orderDetail.setSalePrice(inventoryMap.get(orderDetail.getInventoryId()).getSalePrice());
				//compOpenStoreDetailPrice(experience, orderObject, orderDetail,inventoryMap);
				orderDetail.setSettlementPrice(inventoryMap.get(orderDetail.getInventoryId()).getSettlementPrice());
				orderDetail.setTotalPrice(orderDetail.getSalePrice() * orderDetail.getQuantity());
				orderDetail.setTotalSettlementprice(inventoryMap.get(orderDetail.getInventoryId()).getSettlementPrice() * orderDetail.getQuantity());

				//商品优惠抵扣金额（按商品销售应付金额占总交易应付金额比例分摊总优惠抵扣金额）
				int odPomotionDiscount = compODPomotionDiscount(userPromotion, orderObject, orderDetail, bgSalePriceMap);
				if (odPomotionDiscount == -1) {
					odPomotionDiscount = 0;
				} else {//按订单记录最后一个商品优惠抵扣金额
					int[] LastPomotionDiscountArr = { j, odPomotionDiscount };
					odLastPomotionDiscountMap.put(orderDetail.getOrderId(), LastPomotionDiscountArr);
				}
				orderDetail.setPromotionDiscount(odPomotionDiscount);

				//现金币
				int cashCoin = ((Double) (orderDetail.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * orderObject.getCashCoin())).intValue();
				//店铺订单最后一行商品明细处理精度缺失
				if (j == requestOrderDetail.getOrderDetailList().size() - 1 || orderDetail.getStoreId().intValue() != requestOrderDetail.getOrderDetailList().get(j + 1).getStoreId().intValue()) {
					cashCoin = orderInfoIdMap.get(orderDetail.getOrderId()).getCashCoin() - (odAllCashCoinMap.get(orderDetail.getOrderId()) != null ? odAllCashCoinMap.get(orderDetail.getOrderId()) : 0);
				}
				orderDetail.setCashCoin(cashCoin);

				//商品应付金额
				int totalFee = orderDetail.getTotalPrice() - orderDetail.getPromotionDiscount() - orderDetail.getCashCoin();
				if (totalFee <= 0) {// 如果应付金额小于0，默认为0
					totalFee = 0;
				}
				//当订单应付金额累加大于等于实际订单应付总金额,当前应付为订单实际应付总金额-以累加订单商品应付金额=当前订单商品应付金额（用于处理精度缺失问题）
				if (((odAllTotalFeeMap.get(orderDetail.getOrderId()) != null ? odAllTotalFeeMap.get(orderDetail.getOrderId()) : 0) + totalFee) >= orderInfoIdMap.get(orderDetail.getOrderId()).getTotalFee()) {
					totalFee = orderInfoIdMap.get(orderDetail.getOrderId()).getTotalFee() - (odAllTotalFeeMap.get(orderDetail.getOrderId()) != null ? odAllTotalFeeMap.get(orderDetail.getOrderId()) : 0);
				}
				orderDetail.setTotalFee(totalFee);

				// orderDetail.setTalentAgio(talentAgio);
				//按订单分类，累加商品应付金额
				if (odAllTotalFeeMap.get(orderDetail.getOrderId()) == null) {
					odAllTotalFeeMap.put(orderDetail.getOrderId(), totalFee);
				} else {
					odAllTotalFeeMap.put(orderDetail.getOrderId(), (odAllTotalFeeMap.get(orderDetail.getOrderId()) != null ? odAllTotalFeeMap.get(orderDetail.getOrderId()) : 0) + totalFee);
				}
				//按订单分类，累加现金币
				if (odAllCashCoinMap.get(orderDetail.getOrderId()) == null) {
					odAllCashCoinMap.put(orderDetail.getOrderId(), cashCoin);
				} else {
					odAllCashCoinMap.put(orderDetail.getOrderId(), (odAllCashCoinMap.get(orderDetail.getOrderId()) != null ? odAllCashCoinMap.get(orderDetail.getOrderId()) : 0) + cashCoin);
				}
				//按订单分类，累加优惠抵扣金额
				if (odAllPomotionDiscountMap.get(orderDetail.getOrderId()) == null) {
					odAllPomotionDiscountMap.put(orderDetail.getOrderId(), odPomotionDiscount);
				} else {
					odAllPomotionDiscountMap.put(orderDetail.getOrderId(), (odAllPomotionDiscountMap.get(orderDetail.getOrderId()) != null ? odAllPomotionDiscountMap.get(orderDetail.getOrderId()) : 0) + odPomotionDiscount);
				}
			}
			//计算每个店铺订单最后一个商品的优惠抵扣金额（用于处理分摊优惠抵扣时的精度缺失）
			for (Map.Entry<Long, int[]> entry : odLastPomotionDiscountMap.entrySet()) {
				int[] arr = entry.getValue();
				OrderDetail orderDetail = requestOrderDetail.getOrderDetailList().get(arr[0]);
				if (odAllPomotionDiscountMap.get(orderDetail.getOrderId()) != null) {
					requestOrderDetail.getOrderDetailList().get(arr[0]).setPromotionDiscount(orderInfoIdMap.get(orderDetail.getOrderId()).getPromotionDiscount() - (odAllPomotionDiscountMap.get(orderDetail.getOrderId()) - arr[1]));
				}
			}
			//批量保存订单商品明细
			int odResult = orderDao.batchInsertOrderDetail(requestOrderDetail.getOrderDetailList());
			if (odResult != 1) {
				throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
			}

			//计算分佣
			addCommision(user, orderObject, inventoryMap, orderInfoIdMap, baseRestrictionsMap);

			if (orderObject.getCashCoin() > 0) {//记录现金币使用流水
				UserJournal userJournal = new UserJournal();
				userJournal.setUserId(orderObject.getUserId());
				userJournal.setOrderSn(orderObject.getOrderSn());
				userJournal.setPromotionDetailId(orderObject.getPromotionId());
				userJournal.setMoney(orderObject.getCashCoin());
				userJournal.setComment("订单消费");
				userJournal.setStatus(UserJournalStatusEnum.S7.getCode());
				userJournal.setType(CommonConstants.USER_JOURNAL_TYPE_SUB);
				int ujResult = userJournalService.insertUserJournal(userJournal);
				if (ujResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
			}
		} catch (PlatformException pe) {
			result = "error";
			logger.error(pe.getMessage(), pe);
			throw new PlatformException(pe.getErrorEnum(), pe.getMessage());
		} catch (Exception e) {
			result = "error";
			logger.error(e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
		return result;
	}

	private CompanyXzVo setCompany(Long userID) {
		if (userID == null) {
			return null;
		}
		TalentJob talentJob = null;
		// 获取讲师
		try {
			talentJob = talentJobSerice.getTalentJobByUserId(userID);
		} catch (TooManyResultsException e) {
			logger.error("根据讲师userID[{}]找到多条讲师信息", userID);
			throw new PlatformException(ErrorEnum.C20107, "一个讲师对应多条讲师信息");
		}
		if (talentJob == null) {
			return null;
		}
		CompanyXzVo companyXz = companyService.selectByBranchId(talentJob.getBranchId());
		if (companyXz == null) {
			return null;
		} else {
			companyXz.setJobNo(talentJob.getJobNo());
		}
		return companyXz;
	}

	private CompanyXzVo setCompany(String jzgs_persion_id) {
		if (StringUtils.isBlank(jzgs_persion_id)) {
			// 无讲师 默认为公共讲师(GZ106163)
			jzgs_persion_id = BaseConstants.XZ_SISTER_PERSION_ID;
		}
		TalentJob talentJob = null;
		// 获取讲师
		try {
			talentJob = talentJobSerice.selectTalentJobByPersonId(jzgs_persion_id);
		} catch (TooManyResultsException e) {
			logger.error("根据讲师身份[{}]找到多条讲师信息", jzgs_persion_id);
			throw new PlatformException(ErrorEnum.C20107, "一个讲师对应多条讲师信息");
		}
		if (talentJob == null) {
			throw new PlatformException(ErrorEnum.C20107, "未找到记账公司");
		}
		CompanyXzVo companyXz = companyService.selectByBranchId(talentJob.getBranchId());
		if (companyXz == null) {
			logger.error("讲师[{}]所属分公司[{}]为空", talentJob.getJobNo(), talentJob.getBranchId());
			throw new PlatformException(ErrorEnum.C20700, ErrorEnum.C20700.getMessage());
		} else {
			companyXz.setJobNo(talentJob.getJobNo());
		}
		return companyXz;
	}

	/**
	 * <dl>
	 * <dt>获取订单所属分公司(分公司找不到 就默认为欲妆公共讲师的所属公司)</dt>
	 * </dl>
	 * @param user 购买人
	 * @param talentJob 讲师信息（用户id，讲师编号）
	 * @param companyXz 讲师所属分公司
	 * @param inOrderDetailList
	 * @return CompanyXzVo
	 * @author gwq
	 * @Date 2017-10-30 14:00:00
	 */
	protected CompanyXzVo setCompany(ResponseUser user, TalentJob talentJob, CompanyXzVo companyXz, List<OrderDetail> inOrderDetailList) throws Exception {
		String recommendFrom = null;// 身份id
		if (inOrderDetailList.get(0).getTalentId() != null && inOrderDetailList.get(0).getTalentId().longValue() > 0) {// 达人分享商品，如果分享人是讲师取此达人的推荐人身份id，如果不是讲师达人取此达人的分享达人身份id
			ResponseUser recommendFromUser = userService.selectUserRoleById(inOrderDetailList.get(0).getTalentId());
			if (recommendFromUser.getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {
				recommendFrom = recommendFromUser.getRecommendFrom();
			} else if (recommendFromUser.getLevel() >= CommonConstants.TALENT_MIN_LEVEL && recommendFromUser.getLevel() <= CommonConstants.TALENT_MAX_LEVEL) {
				recommendFrom = recommendFromUser.getTalentTeacher();
			}
		} else {// 不是达人分享商品，取购买人推荐人身份id，如果此人的普通推荐人不是达人讲师取此人普通推荐人的达人导师身份id
			recommendFrom = user.getRecommendFrom();
			ResponseUser recommendFromUser = userService.selectUserRoleByPersonId(recommendFrom);
			if (recommendFromUser != null && recommendFromUser.getLevel() != CommonConstants.TALENT_TEACHER_LEVEL) {
				recommendFrom = recommendFromUser.getTalentTeacher();
			}
		}
		if (recommendFrom == null || recommendFrom.isEmpty()) {
			//  无讲师 默认为公共讲师(GZ106163)
			recommendFrom = BaseConstants.XZ_SISTER_PERSION_ID;
		}
		// 获取讲师
		try {
			talentJob = talentJobSerice.selectTalentJobByPersonId(recommendFrom);
		} catch (TooManyResultsException e) {
			logger.error("根据讲师身份[{}]找到多条讲师信息", recommendFrom);
			throw new PlatformException(ErrorEnum.C20107, "一个讲师对应多条讲师信息");
		}
		if (talentJob == null) {// 推荐人不是讲师 默认为公共讲师(GZ106163)
			talentJob = talentJobSerice.selectTalentJobByPersonId(BaseConstants.XZ_SISTER_PERSION_ID);
		}
		String result = HttpUtil.doPost("userName=" + talentJob.getJobNo(), Config.getString("xz.getUser"), null);
		OrderForThirdResponseXzResult<OrderForXZTeacherVo> orderForThirdResponseXzResult = new OrderForThirdResponseXzResult<OrderForXZTeacherVo>(new OrderForXZTeacherVo());
		orderForThirdResponseXzResult = JSON.parseObject(result, new TypeReference<OrderForThirdResponseXzResult<OrderForXZTeacherVo>>() {});
		String branchId = null;
		if (orderForThirdResponseXzResult.getResult()) {
			branchId = orderForThirdResponseXzResult.getData().getBranchId();
		} else {
			logger.error("talentJob.getJobNo()=" + talentJob.getJobNo());
			throw new PlatformException(ErrorEnum.C20700, ErrorEnum.C20700.getMessage());
		}
		companyXz = companyService.selectByBranchId(branchId);
		if (companyXz == null) {
			logger.error("讲师[{}]所属分公司[{}]为空", talentJob.getJobNo(), branchId);
			throw new PlatformException(ErrorEnum.C20700, ErrorEnum.C20700.getMessage());
		} else {
			companyXz.setJobNo(talentJob.getJobNo());
		}
		return companyXz;
	}

	/**
	 * 开店店铺类型
	 * @param user 当前用户
	 * @param orderObject 父订单
	 * @param shareRecommendUserMap
	 * @param talentIdAndUserReMap
	 * @param talentId 达人id
	 * @return OpenStoreTypeEnum 开店类型
	 * @author zls
	 */
	protected OpenStoreTypeEnum checkOpenStoreCommision(ResponseUser user, OrderObject orderObject, Map<String, ResponseUser> shareRecommendUserMap, Map<Long, ResponseUser> talentIdAndUserReMap, long talentId) {
		return OpenStoreTypeEnum.T0;
	}

	/**
	 * <dl>
	 * <dt>开店商品直接分佣应得金额</dt>
	 * </dl>
	 * @param openStoreTypeEnum 开店单类型
	 * @param commisionPrice 商品应付金额
	 * @param baseRestrictionsMap 基础配置信息集合
	 * @param fee 正常应得分佣金额
	 * @param inventoryMap 商品信息集合（以库存id为索引）
	 * @param orderDetail 当前商品
	 * @return int 实际应得分佣金额
	 * @author zls
	 */
	protected int openStoreCommision(OpenStoreTypeEnum openStoreTypeEnum, int commisionPrice, Map<String, BaseRestrictions> baseRestrictionsMap, int fee, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		return fee;
	}

	/**
	 * <dl>
	 * <dt>开店单直接分佣描述</dt>
	 * </dl>
	 * @param openStoreTypeEnum 开店单类型
	 * @param comment 分佣描述
	 * @param inventoryMap 购买商品信息集合（以库存id为索引）
	 * @param orderDetail 当前购买商品
	 * @return String 分佣描述
	 * @author zls
	 */
	protected String openStoreComment(OpenStoreTypeEnum openStoreTypeEnum, String comment, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		return comment;
	}

	/**
	 * <dl>
	 * <dt>二次分佣应得金额</dt>
	 * </dl>
	 * @param openStoreTypeEnum 开店单类型
	 * @param commisionPrice 商品应付金额
	 * @param baseRestrictionsMap 基础配置信息集合
	 * @param fee 正常应得分佣金额
	 * @param inventoryMap 商品信息集合（以库存id为索引）
	 * @param orderDetail 当前商品
	 * @return int
	 * @author zls
	 */
	protected int openStoreCommision2(OpenStoreTypeEnum openStoreTypeEnum, int commisionPrice, Map<String, BaseRestrictions> baseRestrictionsMap, int fee, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		return fee;
	}

	@Override
	public boolean addCommision(ResponseUser loginUser, OrderObject orderObject, Map<Long, InventoryVo> inventoryMap, Map<Long, OrderInfo> orderInfoIdMap, Map<String, BaseRestrictions> baseRestrictionsMap) throws PlatformException {
		return addCommision(loginUser, orderObject, inventoryMap, orderInfoIdMap);
	}

	@Override
	public boolean addCommision(ResponseUser loginUser, OrderObject orderObject, Map<Long, InventoryVo> inventoryMap, Map<Long, OrderInfo> orderInfoIdMap) throws PlatformException {
		boolean result = false;
		try {
			if (orderObject.getTotalFee().intValue() > 0) {//做分步计算 插入数据(零元付除外)
				//打开分步计算
				OrderSettlementCommision record = new OrderSettlementCommision();
				record.setCreateTime(DateUtil.getNow());
				record.setUpdateTime(DateUtil.getNow());
				record.setOrderObjectId(orderObject.getId());
				record.setOrderSn(orderObject.getOrderSn());
				result = orderSettlementCommisionMapper.insert(record) > 0 ? true : false;
			} else if (orderObject.getStatus() == OrderStatusEnum.S2.getCode() && StringUtils.isNotBlank(orderObject.getPayId()) && StringUtils.isNotBlank(orderObject.getPayTime())) { //零元付进消息队列{已支付 状态为代发货 有付款时间和支付ID}
				OrderSettlementCommision record = new OrderSettlementCommision();
				record.setCreateTime(DateUtil.getNow());
				record.setUpdateTime(DateUtil.getNow());
				record.setOrderObjectId(orderObject.getId());
				record.setOrderSn(orderObject.getOrderSn());
				record.setStatus(3);//加入队列 等待事务完成之后 在处理消息
				orderSettlementCommisionMapper.insertALL(record);
				orderQueueService.createCommision(createMessageProperties(orderObject.getOrderSn(),orderObject.getOrderSn()));
			}
		} catch (PlatformException pe) {
			result = false;
			logger.error(pe.getMessage(), pe);
			throw new PlatformException(pe.getErrorEnum(), pe.getMessage());
		} catch (Exception e) {
			result = false;
			logger.error(e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
		return result;
	}

	/**
	 * <dl>
	 * <dt>2018-02-08版本新佣金计算</dt>
	 * </dl>
	 * @param orderObjectList
	 * @return List<Commision>
	 * @author gaoweiqi
	 * @date 2017年8月19日 12:44:05
	 */
	private boolean addCommisionSettment(ResponseUser loginUser, OrderObject orderObject, Map<Long, InventoryVo> inventoryMap, Map<Long, OrderInfo> orderInfoIdMap) throws PlatformException {
		boolean result = false;
		try {
			int orderObjectCommisionFee = 0;//交易累计分佣金额，单位 分
			int realCommisionFee = 0;//实际分佣金额
			int orderObjectPointFee = 0;//交易累计妆币，单位 分
			List<Commision> commisionList = new ArrayList<Commision>();//余额分佣事务明细
//			List<CUserPointTransaction> _add_user_point_list = new ArrayList<CUserPointTransaction>();//积分事务明细
			List<OrderDetail> inOrderDetailList = orderDao.selectOrderDetilByOrderObjectId(orderObject.getId());//订单商品明细
			long storeUserID = orderObject.getOpenStoreUserId();//店中店用户ID
			if (storeUserID == 0) {
				throw new PlatformException("获取店主id失败");
			}
			if (orderObject.getOpenStore() == 1) {//开店商品分佣开始计算
				//判断当前开店单是否异常
				if (orderInfoIdMap == null || orderInfoIdMap.size() > 1) {
					throw new PlatformException("开店单的子单异常");
				}
				if (inOrderDetailList == null || inOrderDetailList.size() > 1 || inOrderDetailList.get(0).getQuantity() > 1) {
					throw new PlatformException("开店单的商品明细单异常");
				}
				OrderDetail OpenStoreOrderDetail = inOrderDetailList.get(0);
				OrderInfo OpenStoreOrderInfo = orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId());
				if (OpenStoreOrderDetail == null || OpenStoreOrderInfo == null) {
					throw new PlatformException("获取子单 明细单为空");
				}
				//获取开店分佣配置文件 并检查基础配置信息文件
				BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("open_store_commision_config" + "_" + OpenStoreOrderDetail.getGoodId());
				if (baseRestrictions == null) {
					throw new PlatformException("缺少配置文件");
				}
				Map<String, List<UserCommision>> openStoreCommisionConfigMap = JSONObject.parseObject(baseRestrictions.getName(), Map.class);
				if (openStoreCommisionConfigMap == null || openStoreCommisionConfigMap.size() == 0) {
					throw new PlatformException("配置文件没有内容");

				}
				int calculationNum = 0;//最多查询两次 超过两次说明可能死循环
				//获取配置信息完成 开始计算佣金
				//获取分佣类型
				StringBuffer Buffer = new StringBuffer();
				ResponseUser TempUser = userService.selectUserRoleById(storeUserID);
				ResponseUser supervision = TempUser;//顶级角色 督导
				Map<Integer, Long> userRoleIDMap = new HashMap<Integer, Long>();
				Buffer.append(TempUser.getRoleId());
				userRoleIDMap.put(TempUser.getRoleId(), TempUser.getUserId());
				while (TempUser.getRoleId() != RoleEnum.R11.getCode() && StringUtils.isNotBlank(TempUser.getTalentTeacher()) && calculationNum < CALCULATION_NUM) {//有上级 同时不能超过最大查询次数 目前最多两次
					TempUser = userService.selectUserRoleByPersonId(TempUser.getTalentTeacher());
					Buffer.append("|").append(TempUser.getRoleId());
					userRoleIDMap.put(TempUser.getRoleId(), TempUser.getUserId());
					calculationNum++;
					supervision = TempUser.getRoleId() == RoleEnum.R11.getCode() ? TempUser : null;
				}
				if (openStoreCommisionConfigMap.get(Buffer.toString()) == null) {
					logger.error("开店配置文件中未找到此分佣类型：{}", Buffer.toString());
					throw new PlatformException("配置文件中未找到此分佣类型:" + Buffer.toString());
				}
				//生成积分事务
				int commisionPrice = OpenStoreOrderDetail.getTotalFee() + OpenStoreOrderDetail.getCashCoin() + OpenStoreOrderDetail.getBalancePaid();//商品应付金额（分佣基数）
				/*int feeSaleRate = commisionPrice * inventoryMap.get(OpenStoreOrderDetail.getInventoryId()).getScoreRate() / 100;//可获得消费积分 (交易总金额*消费积分率)
				if (feeSaleRate > 0) {
					CUserPointTransaction _add_user_point_transaction = new CUserPointTransaction();
					_add_user_point_transaction.setTransactionStatus(orderObject.getTotalFee() == 0 ? 0 : -1);//未处理
					_add_user_point_transaction.setCreatorId(loginUser.getUserId());
					_add_user_point_transaction.setCreatorName(loginUser.getNickName());
					createUserPoint(_add_user_point_transaction, OpenStoreOrderDetail, feeSaleRate, 0, "消费送积分", 12, loginUser.getUserId());
					_add_user_point_list.add(_add_user_point_transaction);
					orderObjectPointFee += feeSaleRate;
					//累加订单积分金额
					orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).setPointFee(orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).getPointFee() + feeSaleRate);
				}*/
				//根据配置信息 生成佣金
				for (Object Obj : openStoreCommisionConfigMap.get(Buffer.toString())) {
					UserCommision UserCommision = JsonUtil.toBean(Obj.toString(), UserCommision.class);
					if (UserCommision.getShowCommisionFee() > 0 || UserCommision.getHideCommisionFee() > 0) {//有效佣金
						//开始计算分佣
						Commision openStoreCommision = new Commision();
						openStoreCommision.setStatus(0);//禁用
						openStoreCommision.setResult(0);//未处理
						createOpenStoreCommision(openStoreCommision, OpenStoreOrderDetail, UserCommision.getShowCommisionFee().intValue(), "开店分佣", 1, userRoleIDMap.get(UserCommision.getRoleID().intValue()), String.valueOf(UserCommision.getRoleID()), UserCommision.toString(), String.valueOf(UserCommision.getHideCommisionFee()));
						commisionList.add(openStoreCommision);
						//累计交易单总分佣金额（元）
						orderObjectCommisionFee += UserCommision.getShowCommisionFee();
						realCommisionFee += (UserCommision.getShowCommisionFee() + UserCommision.getHideCommisionFee());
						//累计每笔订单分佣总金额（元）
						orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).setCommisionFee(UserCommision.getShowCommisionFee().intValue() + orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).getCommisionFee());
					}
				}
				// 督导培养出来的新督导 佣金计算 begin
				if (baseRestrictions.getStatus() == 1 && supervision != null && supervision.getRoleId() == RoleEnum.R11.getCode().intValue()) {// 佣金额外计算

					if (StringUtils.isNotBlank(supervision.getTalentTeacher()) && baseRestrictions.getRestrictions() == 20000 && baseRestrictions.getExperience() == 240000) {// 399开店包顶级督导计算规则
						ResponseUser supervisionUp1 = userService.selectUserRoleByPersonId(supervision.getTalentTeacher());// 顶级督导的上级
						if (supervisionUp1 == null) {
							logger.error("未找到督导上级 身份id：{}", supervision.getTalentTeacher());
							throw new PlatformException("未找到督导上级 身份id:" + supervision.getTalentTeacher());
						}
						int commisionfEE = 0;
						List<Integer> userids = userMapper.selectSupervisionBypersionID(supervision.getTalentTeacher());
						int supervisioSum = userids.size();// 下属督导数量
						if (supervisioSum >= 6) {// 给4000
							commisionfEE = 4000;
						} else {
							commisionfEE = 2000;
						}
						// 开始计算分佣
						Commision openStoreCommision = new Commision();
						openStoreCommision.setStatus(0);// 禁用
						openStoreCommision.setResult(0);// 未处理
						createOpenStoreCommision(openStoreCommision, OpenStoreOrderDetail, 0, "开店分佣", 1, supervisionUp1.getUserId(), String.valueOf(supervisionUp1.getRoleId()), userids.toString(), String.valueOf(commisionfEE));
						commisionList.add(openStoreCommision);
						// 累计交易单总分佣金额（元）
						orderObjectCommisionFee += openStoreCommision.getFee();
						realCommisionFee += (openStoreCommision.getFee() + commisionfEE);
						// 累计每笔订单分佣总金额（元）
						orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).setCommisionFee(openStoreCommision.getFee() + orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).getCommisionFee());
					} else if (baseRestrictions.getRestrictions() == 5000 && baseRestrictions.getExperience() == 5000&&realCommisionFee<5000) {// 99元开店包
						long userId = 0L;
						int roleid = 0;
						// 设置分佣人的id
						if (StringUtils.isBlank(supervision.getTalentTeacher())) {// 没有上级 自己 拿线下10元
							userId = supervision.getUserId();
							roleid = supervision.getRoleId();
						} else {
							ResponseUser supervisionUp1 = userService.selectUserRoleByPersonId(supervision.getTalentTeacher());// 顶级督导的上级
							if (supervisionUp1 == null) {
								logger.error("未找到督导上级 身份id：{}", supervision.getTalentTeacher());
								throw new PlatformException("未找到督导上级 身份id:" + supervision.getTalentTeacher());
							}
							userId = supervisionUp1.getUserId();
							roleid = supervisionUp1.getRoleId();
						}
						int commisionfEE = 1000;
						// 开始计算分佣
						Commision openStoreCommision = new Commision();
						openStoreCommision.setStatus(0);// 禁用
						openStoreCommision.setResult(0);// 未处理
						createOpenStoreCommision(openStoreCommision, OpenStoreOrderDetail, 0, "开店分佣", 1, userId, String.valueOf(roleid), "", String.valueOf(commisionfEE));
						commisionList.add(openStoreCommision);
						// 累计交易单总分佣金额（元）
						orderObjectCommisionFee += openStoreCommision.getFee();
						realCommisionFee += (openStoreCommision.getFee() + commisionfEE);
						// 累计每笔订单分佣总金额（元）
						orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).setCommisionFee(openStoreCommision.getFee() + orderInfoIdMap.get(OpenStoreOrderDetail.getOrderId()).getCommisionFee());
					}
				}
				// 督导培养出来的新督导 佣金计算 end

				if (!(baseRestrictions.getRestrictions() <= realCommisionFee && realCommisionFee <= baseRestrictions.getExperience())) {
					logger.error("佣金计算错误和配置文件不一致 订单号:{} 实际计算:{} 配置文件：{}", orderObject.getOrderSn(), realCommisionFee, baseRestrictions.getExperience());
					throw new PlatformException("佣金计算错误和配置文件不一致");
				}
			} else {//正常商品分佣开始计算
				BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("goods_commision_config");//次级分佣
				if (baseRestrictions == null) {
					throw new PlatformException("次级分佣 缺少配置文件");
				}
				Map<String, List<UserNormalCommision>> goodsCommisionConfigMap = JSONObject.parseObject(baseRestrictions.getName(), Map.class);
				if (goodsCommisionConfigMap == null || goodsCommisionConfigMap.size() == 0) {
					throw new PlatformException("次级分佣  配置文件没有内容");
				}
				List<GoodsCommission> goodsCommissionList = orderDao.selectGoodsCommissionListInGoodId(inOrderDetailList);//商品分佣信息
				List<LimitTimeSaleGoodsCommission> limitTimeSalegoodsCommissionList = orderDao.selectLimitTimeSaleGoodsCommissionListInGoodId(inOrderDetailList);//分时抢购商品分佣信息
				//以商品id+角色id为索引商品分佣信息集合
				Map<String, GoodsCommission> goodsCommissionMap = new HashMap<String, GoodsCommission>();
				Map<String, LimitTimeSaleGoodsCommission> limitTimeSalegoodsCommissionMap = new HashMap<String, LimitTimeSaleGoodsCommission>();
				for (GoodsCommission goodsCommission : goodsCommissionList) {
					goodsCommissionMap.put(goodsCommission.getGoodId() + "_" + goodsCommission.getRoleId(), goodsCommission);
				}
				for (LimitTimeSaleGoodsCommission limitTimeSaleGoodsCommission : limitTimeSalegoodsCommissionList) {
					limitTimeSalegoodsCommissionMap.put(limitTimeSaleGoodsCommission.getGoodId() + "_" + limitTimeSaleGoodsCommission.getRoleId(), limitTimeSaleGoodsCommission);
				}

				//获取分佣信息
				int calculationNum = 0;//最多查询两次 超过两次说明可能死循环
				//获取配置信息完成 开始计算佣金
				//获取分佣类型
				StringBuffer Buffer = new StringBuffer();
				ResponseUser TempUser1 = userService.selectUserRoleById(storeUserID);
				ResponseUser StoreUser = TempUser1;
				Map<Integer, Long> userRoleIDMap = new HashMap<Integer, Long>();
				Buffer.append(TempUser1.getRoleId());
				userRoleIDMap.put(TempUser1.getRoleId(), TempUser1.getUserId());
				while (TempUser1.getRoleId() != RoleEnum.R11.getCode() && StringUtils.isNotBlank(TempUser1.getTalentTeacher()) && calculationNum < CALCULATION_NUM) {//有上级 同时不能超过最大查询次数 目前最多两次
					TempUser1 = userService.selectUserRoleByPersonId(TempUser1.getTalentTeacher());
					Buffer.append("|").append(TempUser1.getRoleId());
					userRoleIDMap.put(TempUser1.getRoleId(), TempUser1.getUserId());
					calculationNum++;
				}
				if (goodsCommisionConfigMap.get(Buffer.toString()) == null) {
					logger.error("普通商品分佣配置文件中未找到此分佣类型：{}", Buffer.toString());
					throw new PlatformException("普通商品分佣配置文件中未找到此分佣类型");
				}
				//开始分佣
				for (OrderDetail orderDetail : inOrderDetailList) {
					//生成积分事务
					int commisionPrice = orderDetail.getTotalFee() + orderDetail.getCashCoin() + orderDetail.getBalancePaid();//商品应付金额（分佣基数）
					/*int feeSaleRate = commisionPrice * inventoryMap.get(orderDetail.getInventoryId()).getScoreRate() / 100;//可获得消费积分 (交易总金额*消费积分率)
					if (feeSaleRate > 0) {
						CUserPointTransaction _add_user_point_transaction = new CUserPointTransaction();
						_add_user_point_transaction.setTransactionStatus(orderObject.getTotalFee() == 0 ? 0 : -1);//未处理
						_add_user_point_transaction.setCreatorId(loginUser.getUserId());
						_add_user_point_transaction.setCreatorName(loginUser.getNickName());
						createUserPoint(_add_user_point_transaction, orderDetail, feeSaleRate, 0, "消费送积分", 12, loginUser.getUserId());
						_add_user_point_list.add(_add_user_point_transaction);
						orderObjectPointFee += feeSaleRate;
						//累加订单积分金额
						orderInfoIdMap.get(orderDetail.getOrderId()).setPointFee(orderInfoIdMap.get(orderDetail.getOrderId()).getPointFee() + feeSaleRate);
					}*/
					//计算初级佣金
					//封装商品分佣信息key（以商品id+角色id）
					String goodsCommissionKey = "";
					goodsCommissionKey = orderDetail.getGoodId() + "_" + StoreUser.getRoleId();
					String extend2 = "";//分佣计算比例记录
					GoodsCommission goodsCommission = null;//分佣比例
					/*计算直卖分佣*/
					boolean isLimitGoods = orderDetail.getLimitTimeSaleId() > 0 ? true : false;//是否是分时抢购产品
					//获取分时抢购的分佣信息
					if (isLimitGoods && limitTimeSalegoodsCommissionMap.get(goodsCommissionKey) != null) {
						goodsCommission = new GoodsCommission();
						goodsCommission.setLimitTimeSalegoodsCommission(limitTimeSalegoodsCommissionMap.get(goodsCommissionKey));
						extend2 = limitTimeSalegoodsCommissionMap.get(goodsCommissionKey).toString();
					} else if ((!isLimitGoods) && goodsCommissionMap.get(goodsCommissionKey) != null) {//不是分时抢购
						goodsCommission = new GoodsCommission();
						goodsCommission = goodsCommissionMap.get(goodsCommissionKey);
						extend2 = goodsCommission.toString();
					}
					if (goodsCommission != null) { //商品分佣信息存在
						//分佣比例存在 学生店计算分佣   直卖分佣
						Commision _add_direct_commision = new Commision();
						if (orderObject.getTotalFee() == 0) {//0元付
							_add_direct_commision.setStatus(1);//可用
							_add_direct_commision.setResult(0);//未处理

						} else {//待付款
							_add_direct_commision.setStatus(0);//禁用
							_add_direct_commision.setResult(0);//未处理
						}
						String extend1 = "";//分佣计算模式
						//分佣类型 默认直卖
						String comment = CommonConstants.COMMISION_DESC_SHARE;

						/*-----------计算分佣金额 begin-------------*/
						int fee = 0;
						if (goodsCommission.getCommissionType() == 1) {//分佣比例类型  1 按比例取值佣
							fee = commisionPrice * goodsCommission.getCommission() / 100;//百分比计算
							extend1 = "比例计算";
						} else {// 2 按金额取值分佣
							fee = orderDetail.getQuantity() * goodsCommission.getCommission();
							extend1 = "金额计算";
						}
						createCommision(_add_direct_commision, orderDetail, fee, comment, 2, StoreUser.getUserId(), extend1, extend2, "");
						commisionList.add(_add_direct_commision);
						//累计交易单总分佣金额（元）
						orderObjectCommisionFee += _add_direct_commision.getFee();
						//累计每笔订单分佣总金额（元）
						orderInfoIdMap.get(orderDetail.getOrderId()).setCommisionFee(_add_direct_commision.getFee() + orderInfoIdMap.get(orderDetail.getOrderId()).getCommisionFee());
						//计算次级分佣
						for (Object JsonObj : goodsCommisionConfigMap.get(Buffer.toString())) {
							UserNormalCommision UserCommision = JsonUtil.toBean(JsonObj.toString(), UserNormalCommision.class);
							if (UserCommision.isCalculate()) {//是否计算
								//开始计算分佣
								Commision goodsCommision = new Commision();
								if (orderObject.getTotalFee() == 0) {//0元付
									goodsCommision.setStatus(1);//可用
									goodsCommision.setResult(0);//未处理
								} else {//待付款
									goodsCommision.setStatus(0);//禁用
									goodsCommision.setResult(0);//未处理
								}
								if (UserCommision.isIshide()) {//隐藏
									createCommision(goodsCommision, orderDetail, 0, "间接分佣", 3, userRoleIDMap.get(UserCommision.getRoleID()), String.valueOf(UserCommision.getRoleID()), UserCommision.toString(), String.valueOf(UserCommision.getCommisionProportion() * _add_direct_commision.getFee() / 100));
								} else {//显示
									createCommision(goodsCommision, orderDetail, UserCommision.getCommisionProportion() * _add_direct_commision.getFee() / 100, "间接分佣", 3, userRoleIDMap.get(UserCommision.getRoleID()), String.valueOf(UserCommision.getRoleID()), UserCommision.toString(), "");
								}
								commisionList.add(goodsCommision);
								//累计交易单总分佣金额（元）
								orderObjectCommisionFee += goodsCommision.getFee();
								//累计每笔订单分佣总金额（元）
								orderInfoIdMap.get(orderDetail.getOrderId()).setCommisionFee(goodsCommision.getFee() + orderInfoIdMap.get(orderDetail.getOrderId()).getCommisionFee());
							}
						}
					}
				}
			}
			/** ------------------------佣金计算结束---------------------------------------- */

			//开始计算结算单
			int i = 0;//商品明细循环下标
			long preOrderId = 0;//上一个订单id
			int currSettlementPriceDealer = 0;//累计经销商结算价
			int currCashCoinDealer = 0;//累计经销商现金币
			int currBalancePaidDealer = 0;//累计经销商余额付
			List<OrderSettlement> orderSettlementList = new ArrayList<OrderSettlement>();//结算明细

			for (OrderDetail orderDetail : inOrderDetailList) {
				/*结算信息*/
				boolean isSub = false;
				if (i == inOrderDetailList.size() - 1 || (i != 0 && (i + 1) < inOrderDetailList.size() && inOrderDetailList.get(i + 1).getOrderId().longValue() != orderDetail.getOrderId().longValue())) {
					isSub = true;
				}
				if (orderDetail.getOrderId() != preOrderId) {
					currSettlementPriceDealer = 0;
					currCashCoinDealer = 0;
					currBalancePaidDealer = 0;
				}
				//封装订单商品结算信息
				OrderSettlement orderSettlement = createOrderSettlement(orderInfoIdMap, orderDetail, inventoryMap, null, isSub, currSettlementPriceDealer, currCashCoinDealer, currBalancePaidDealer);
				orderSettlementList.add(orderSettlement);

				//累加经销商结算价、经销商现金币、经销商余额付
				currSettlementPriceDealer += orderSettlement.getSettlementPriceDealer();
				currCashCoinDealer += orderSettlement.getCashCoinDealer();
				currBalancePaidDealer += orderSettlement.getBalancePaidDealer();
				preOrderId = orderDetail.getOrderId();
				i++;
			}
			//生成运费的结算单信息 放入 orderSettlementList
			if (orderObject != null && orderObject.getFreight() != null && orderObject.getFreight().intValue() > 0) {
				createOrderFreightSettlement(orderSettlementList, orderInfoIdMap, inOrderDetailList);
			}

			//批量保存分佣信息
			if (commisionList != null && commisionList.size() > 0) {
				int coResult = orderDao.batchInsertCommision(commisionList);
				if (coResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
			}
			//批量保存积分信息
			/*if (_add_user_point_list != null && _add_user_point_list.size() > 0) {
				int coResult = userPointTransactionMapper.batchInsertPointTransaction(_add_user_point_list);
				if (coResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
			}*/
			//批量保存订单结算明细
			int osResult = orderDao.batchInsertOrderSettlement(orderSettlementList);
			if (osResult != 1) {
				throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
			}

			//交易总分佣或者积分事务金额大于0，更新交易单
			if (orderObjectCommisionFee > 0 || orderObjectPointFee > 0) {
				orderObject.setCommisionFee(orderObjectCommisionFee);
				orderObject.setPointFee(orderObjectPointFee);
				int ooResult = orderDao.updateOrderObjectByPrimaryKeySelective(orderObject);
				if (ooResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
				//批量更新订单分佣金额 妆币数量
				Collection<OrderInfo> orderInfoCollection = orderInfoIdMap.values();
				List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>(orderInfoCollection);
				int oiResult = orderDao.batchUpdateCommisionFeeAndPointFeeById(orderInfoList);
				if (oiResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
			}

			// 更新订单上的公司信息 begin
			CompanyXzVo companyXzVo = null;
			StringBuffer buffer = new StringBuffer();
			ResponseUser companyUser = userService.selectUserRoleById(storeUserID);
			if (companyUser.getRoleId() < RoleEnum.R7.getCode().intValue()) {
				companyUser = userService.selectUserRoleByPersonId(companyUser.getTalentTeacher());
			}
			// 获取订单上的记账公司
			companyXzVo = setCompany(companyUser.getUserId());
			int cycTimes = 0;
			while (companyXzVo == null && !StringUtils.contains(buffer.toString(), companyUser.getTalentTeacher())) {// 导师级别的
				cycTimes++;
				buffer.append(companyUser.getTalentTeacher()).append("|");
				companyUser = userService.selectUserRoleByPersonId(companyUser.getTalentTeacher());
				companyXzVo = setCompany(companyUser.getUserId());
				if (companyXzVo != null) {
					break;
				}
				if (cycTimes > 50) {//防止死循环 不太可能。。。。。
					logger.error("订单查找业绩公司出现死循环:订单:{},persionID链条{}", orderObject.getOrderSn(), buffer.toString());
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
			}
			if (companyXzVo == null) {//没有找到 默认为公共讲师的订单
				companyXzVo = setCompany("");//默认为校妆姐姐的公司
			}
			Collection<OrderInfo> orderInfoCollection = orderInfoIdMap.values();
			List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>(orderInfoCollection);
			for (OrderInfo orderInfo : orderInfoList) {
				int oiResult = orderDao.updateOrderInfoCompanyAndJobNoById(orderInfo.getId(), companyXzVo.getId(), companyXzVo.getJobNo());
				if (oiResult != 1) {
					throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
				}
			}
			//更新订单上的公司信息  end

			//计算收益
			Earnings(commisionList, orderObject);
			result = true;
		} catch (PlatformException pe) {
			result = false;
			logger.error(pe.getMessage(), pe);
			throw new PlatformException(pe.getErrorEnum(), pe.getMessage());
		} catch (Exception e) {
			result = false;
			logger.error(e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
		return result;
	}

	protected void Earnings(List<Commision> commisionList, OrderObject order) {
		try {
			Map<Long, Integer> userCommisionMap = new HashMap<Long, Integer>();
			for (Commision commision : commisionList) {
				Long userID = commision.getUserId();
				Integer fee = commision.getFee();
				if (fee > 0) {//有效收益
					if (userCommisionMap.containsKey(userID)) {
						userCommisionMap.put(userID, userCommisionMap.get(userID) + fee);
					} else {
						userCommisionMap.put(userID, fee);
					}
				}
			}
			userEarningsService.CalculateEarningsOrderWithCache(userCommisionMap, order.getOpenStoreUserId(), (order.getTotalFee() == null ? 0 : order.getTotalFee()) + (order.getBalancePaid() == null ? 0 : order.getBalancePaid()), order.getPayTime());
		} catch (Exception e) {
			logger.error("计算收益失败 相关订单号:{} 错误：{}", order.getOrderSn(), e.getMessage());
		}
	}

	/** 开店单佣金直接到账 */
	protected void OpenStoreCommisionToAccount(OrderObject order, Map<Long, OrderInfo> orderInfoIDMap) throws Exception {
		if (order.getOpenStore() != 1) {//只计算开店单的佣金
			return;
		}
		// 分佣
		logger.warn("--------开店佣金到账---------");
		List<Commision> commisionList = commisionMapper.selectByOrderObjectIdForCommision(order.getId());
		Map<String, OrderInfo> orderInfoSNMap = new HashMap<String, OrderInfo>();
		for (OrderInfo orderInfo : orderInfoIDMap.values()) {
			orderInfoIDMap.put(orderInfo.getId(), orderInfo);
			orderInfoSNMap.put(orderInfo.getOrderSn(), orderInfo);
		}
		// 定义一个单独的用户集合来保存查询过的用户信息
		Map<Long, User> UserMap = new HashMap<Long, User>();// 用户集合
		List<OrderObject> orderObjTemp = new ArrayList<OrderObject>();
		orderObjTemp.add(order);
		Map<String, Map<Long, Integer>> earningsMap = new HashMap<String, Map<Long, Integer>>();// 收益
																								// <订单号,<用户id，收益>>
		List<OrderObject> orderObjectListTemp = new ArrayList<OrderObject>();
		orderObjectListTemp.add(order);
		List<UserJournal> userJournalList = new ArrayList<UserJournal>();// 佣金流水
		// 根据余额事务集合生成流水信息
		for (Commision commision : commisionList) {
			if (orderInfoIDMap.get(commision.getOrderInfoId()) == null) {
				logger.error("---orderInfoId---数据异常" + commision.getOrderInfoId());
				continue;
			}
			String KeepAccountsType = "";
			// 获取佣金的账务类型
			if (orderInfoIDMap.get(commision.getOrderInfoId()).getStoreId().intValue() == StoreTypeEnum.T14.getCode()) {
				KeepAccountsType = KeepAccountsTypeConstants.COMMISSION_SKIN79;
			} else {
				KeepAccountsType = KeepAccountsTypeConstants.COMMISSION_NOSKIN79;
			}
			// 封装分佣流水
			UserJournal userJournal = new UserJournal();
			userJournal.setUserId(commision.getUserId());
			userJournal.setOrderSn(orderInfoIDMap.get(commision.getOrderInfoId()).getOrderSn());
			userJournal.setPromotionDetailId(orderInfoIDMap.get(commision.getOrderInfoId()).getPromotionId());
			userJournal.setMoney(commision.getFee());
			userJournal.setType(CommonConstants.USER_JOURNAL_TYPE_ADD);
			userJournal.setBankId(0);
			userJournal.setStatus(2);
			userJournal.setComment(commision.getComment());
			userJournal.setBusinessTypeId(commision.getBusinessTypeId());
			userJournal.setBusinessTypeName(commision.getBusinessTypeName());
			userJournal.setIsDelete(0);
			userJournal.setCommisionId(commision.getId().intValue());
			userJournal.setKeepAccountsType(KeepAccountsType);
			userJournal.setExtend3(commision.getExtend3());
			userJournalList.add(userJournal);
			// 保存当前分佣人信息
			if (UserMap.get(commision.getUserId()) == null) {
				User CommisionUser = userService.getUser(commision.getUserId());
				if (CommisionUser != null && StringUtils.isNotBlank(CommisionUser.getUserName())) {
					UserMap.put(commision.getUserId(), CommisionUser);
				}
			}
			if (commision.getFee().intValue() > 0 && orderInfoIDMap.get(commision.getOrderInfoId()) != null && orderInfoSNMap.get(orderInfoIDMap.get(commision.getOrderInfoId()).getOrderSn()) != null) {
				OrderInfo info = orderInfoSNMap.get(orderInfoIDMap.get(commision.getOrderInfoId()).getOrderSn());
				// 计算个人所得分佣
				if (earningsMap.get(info.getOrderSn()) == null) {
					Map<Long, Integer> Map = new HashMap<Long, Integer>();
					Map.put(commision.getUserId(), commision.getFee());
					earningsMap.put(info.getOrderSn(), Map);
				} else {
					Map<Long, Integer> Map = earningsMap.get(info.getOrderSn());
					if (Map.get(commision.getUserId()) == null) {
						Map.put(commision.getUserId(), commision.getFee());
					} else {
						Map.put(commision.getUserId(), Map.get(commision.getUserId()) + commision.getFee());
					}
				}
			}
		}
		autoCommision(commisionList, userJournalList);// 不处理订单状态
		logger.info("--------开店佣金到账 end---------");
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.COMMISSION_TO_ACCOUNT_SMS.getText());
		if (earningsMap.size() > 0 && baseRestrictions != null && baseRestrictions.getStatus() == 1) {// 消息推送
																											// 配置信息为发送短息许可
			for (String orderinfoSn : earningsMap.keySet()) {
				for (Long userId : earningsMap.get(orderinfoSn).keySet()) {
					String Phone = UserMap.get(userId).getUserName();
					double commisionFee = earningsMap.get(orderinfoSn).get(userId).doubleValue() / 100;
					String SMS = baseRestrictions.getName().replace("amount", String.valueOf(commisionFee)).replace("orderSn", orderinfoSn);
					smsService.sendMsgJianZhou(false, Phone, SMS);
					// 发送佣金到账微信通知
					notifyWxMsgServiceImpl.sendWxTemplateMsgCommissionArrival(Phone, String.valueOf(commisionFee));
					// 短信日志
					OperationLog log = new OperationLog();
					log.setObjName(Phone);
					log.setModule("CommissionToAccount");
					log.setOperateType("sendSms");
					Long createLongTime = ((new Date().getTime()) / 1000);
					log.setCreatedAt(createLongTime.intValue());
					log.setDescription("佣金到账短信提醒" + "收件人  " + Phone + " 短信内容：" + SMS);
					operationLogMapper.insert(log);
				}
			}
		}
	}

	/**
	 * 封装分佣实体
	 * @param commision
	 * @param orderDetail 商品明细
	 * @param fee 分佣
	 * @param type 分佣类型
	 * @param comment 描述
	 * @param businessType 账务类型ID
	 * @param userId 佣金所属用户ID
	 * @author gwq
	 */
	private void createCommision(Commision commision, OrderDetail orderDetail, int fee, String comment, int businessType, long userId, String extend1, String extend2, String extend3) {
		commision.setOrderDetailId(orderDetail.getId());
		commision.setOrderInfoId(orderDetail.getOrderId());
		commision.setOrderObjectId(orderDetail.getOrderObjectId());
		commision.setUserId(userId);
		commision.setFee(fee);
		commision.setComment(comment);
		commision.setSourceId(orderDetail.getId());//源ID
		commision.setIsCustom(0);//是否手工
		MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(businessType);//账务类型
		commision.setBusinessTypeId(businessType);//类型id
		commision.setBusinessTypeName(moneyBusinessType == null ? "" : moneyBusinessType.getTypeName());//类型名字
		commision.setExtend1(extend1);//佣金是按照比例计算 还是按照金额
		commision.setExtend2(extend2);//分佣记录明细
		commision.setExtend3(extend3);//隐藏宝箱
	}

	/**
	 * 封装分佣实体
	 * @param createOpenStoreCommision
	 * @param orderDetail 商品明细
	 * @param fee 分佣
	 * @param type 分佣类型
	 * @param comment 描述
	 * @param businessType 账务类型ID
	 * @param userId 佣金所属用户ID
	 * @author gwq
	 */
	private void createOpenStoreCommision(Commision commision, OrderDetail orderDetail, int fee, String comment, int businessType, long userId, String extend1, String extend2, String extend3) {
		commision.setOrderDetailId(orderDetail.getId());
		commision.setOrderInfoId(orderDetail.getOrderId());
		commision.setOrderObjectId(orderDetail.getOrderObjectId());
		commision.setUserId(userId);
		commision.setComment(comment);
		commision.setFee(fee);
		commision.setSourceId(orderDetail.getId());//源ID
		commision.setIsCustom(0);//是否手工
		MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(businessType);//账务类型
		commision.setBusinessTypeId(businessType);//类型id
		commision.setBusinessTypeName(moneyBusinessType == null ? "" : moneyBusinessType.getTypeName());//类型名字
		commision.setExtend1(extend1);//当前分佣人的角色
		commision.setExtend2(extend2);//分佣明细记录
		commision.setExtend3(extend3);//当前不显示的金额
	}

	/**
	 * 封装积分事务实体
	 * @param addUserPoint
	 * @param orderDetail 商品明细
	 * @param fee 消费积分
	 * @param type 积分类型
	 * @param comment 描述
	 * @param businessType 账务类型ID
	 * @param userId 妆币所属用户ID
	 * @author gwq
	 */
	private void createUserPoint(CUserPointTransaction addUserPoint, OrderDetail orderDetail, long fee, int type, String comment, int businessType, long userId) {
		addUserPoint.setBusinessTime(new Date());
		addUserPoint.setUserId(userId);
		OrderInfo info = orderInfoMapper.selectByPrimaryKey(orderDetail.getOrderId());
		addUserPoint.setOrderSn(info == null ? null : info.getOrderSn());
		addUserPoint.setOrderDetailId(orderDetail.getId());
		addUserPoint.setOrderObjectId(orderDetail.getOrderObjectId());
		addUserPoint.setAmount(fee);
		addUserPoint.setBusinessSourceId(orderDetail.getOrderObjectId());
		//		addUserPoint.setTransactionStatus(0);//未处理
		addUserPoint.setIsCustom(0);//非手工
		addUserPoint.setIsDelete(0);//没有被删除
		MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(businessType);//账务类型
		addUserPoint.setBusinessTypeId(businessType);//类型id
		addUserPoint.setBusinessTypeName(moneyBusinessType == null ? "" : moneyBusinessType.getTypeName());//类型名字
	}

	protected OrderSettlement createOrderSettlement(Map<Long, OrderInfo> orderInfoIdMap, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap) {
		OrderSettlement orderSettlement = new OrderSettlement();
		OrderInfo orderInfo = orderInfoIdMap.get(orderDetail.getOrderId());
		orderSettlement.setOrderSn(orderInfo.getOrderSn());
		orderSettlement.setOrderDetailId(orderDetail.getId());
		orderSettlement.setOrderStatus(orderInfo.getStatus());
		orderSettlement.setUserId(orderDetail.getUserId());
		orderSettlement.setProductBn(inventoryMap.get(orderDetail.getInventoryId()).getProductBn());
		orderSettlement.setGoodName(inventoryMap.get(orderDetail.getInventoryId()).getGoodName());
		orderSettlement.setGoodId(inventoryMap.get(orderDetail.getInventoryId()).getGoodId());
		orderSettlement.setTotalPrice(orderDetail.getTotalPrice());
		orderSettlement.setTotalSettlementprice(orderDetail.getTotalSettlementprice());
		orderSettlement.setQuantity(orderDetail.getQuantity());
		orderSettlement.setSalePrice(orderDetail.getSalePrice());
		orderSettlement.setSettlementPrice(orderDetail.getSettlementPrice());
		orderSettlement.setCashCoin(orderDetail.getCashCoin());
		orderSettlement.setBalancePaid(orderDetail.getBalancePaid());
		orderSettlement.setPromotionId(orderInfo.getPromotionId());
		orderSettlement.setPromotionDiscount(orderDetail.getPromotionDiscount());
		orderSettlement.setTotalFee(orderDetail.getTotalFee());
		orderSettlement.setOperateCosting(inventoryMap.get(orderDetail.getInventoryId()).getOperateCosting());
		orderSettlement.setPayType(orderInfo.getPayType());
		orderSettlement.setLinkMan(orderInfo.getLinkMan());
		orderSettlement.setMobile(orderInfo.getMobile());
		orderSettlement.setProvince(orderInfo.getProvince());
		orderSettlement.setCity(orderInfo.getCity());
		orderSettlement.setArea(orderInfo.getArea());
		orderSettlement.setStreet(orderInfo.getStreet());
		orderSettlement.setAddress(orderInfo.getAddress());
		orderSettlement.setDeliveryWay(orderInfo.getDeliveryWay());
		orderSettlement.setStoreId(orderDetail.getStoreId());
		orderSettlement.setOrderCreateTime(orderInfo.getCreateTime());
		orderSettlement.setOrderUpdateTime(orderInfo.getUpdateTime());
		orderSettlement.setRemark(orderInfo.getRemark());
		orderSettlement.setSettlementMan(orderInfo.getSettlementMan());
		orderSettlement.setSettlementAccount(orderInfo.getSettlementAccount());
		orderSettlement.setSettlementBank(orderInfo.getSettlementBank());
		return orderSettlement;
	}

	protected OrderSettlement createOrderSettlement(Map<Long, OrderInfo> orderInfoIdMap, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap, CompanyXz companyXz, boolean isSub, int currSettlementPriceDealer, int currCashCoinDealer, int currBalancePaidDealer) {
		return createOrderSettlement(orderInfoIdMap, orderDetail, inventoryMap);
	}

	/**
	 * 封装交易单详细信息
	 * @param orderObject 交易单
	 * @param orderDetail 订单商品
	 * @param requestOrderDetail 用户提交交易单
	 * @param userAddress 用户配送地址
	 * @author zls
	 */
	protected void createOrderObject(OrderObject orderObject, OrderDetail orderDetail, RequestOrderDetail requestOrderDetail, UserAddress userAddress) {
		orderObject.setUserId(orderDetail.getUserId());
		orderObject.setCashCoin(requestOrderDetail.getCashCoin());
		orderObject.setBalancePaid(requestOrderDetail.getBalanceAmount());
		orderObject.setPromotionId(requestOrderDetail.getPromotionId());
		orderObject.setPayType(requestOrderDetail.getPayType());
		orderObject.setMemberDeliveryAddressId(requestOrderDetail.getMemberDeliveryAddressId());
		orderObject.setDeliveryWay(requestOrderDetail.getDeliveryWay());
		orderObject.setIsBill(requestOrderDetail.getIsBill());
		orderObject.setBillType(requestOrderDetail.getBillType());
		orderObject.setBillHeader(requestOrderDetail.getBillHeader());
		orderObject.setTaxpayerNo(requestOrderDetail.getBillTaxpayerNo());
		orderObject.setLinkMan(userAddress.getLinkMan());
		orderObject.setMobile(userAddress.getMobile());
		orderObject.setProvince(userAddress.getProvince());
		orderObject.setCity(userAddress.getCity());
		orderObject.setArea(userAddress.getArea());
		orderObject.setStreet(userAddress.getStreet());
		orderObject.setAddress(userAddress.getAddress());
		// orderObject.setLon(lon);
		// orderObject.setLat(lat);
		orderObject.setRemark(requestOrderDetail.getRemark());
		orderObject.setPayClientSource(requestOrderDetail.getReqHeader().getPhoneType());
	}

	/**
	 * 封装订单信息
	 * @param orderInfo 订单
	 * @param orderDetail 商品信息
	 * @param requestOrderDetail 用户提交交易单
	 * @param storeVo 店铺
	 * @param userAddress 用户配送地址
	 * @author zls
	 */
	protected void createOrderInfo(OrderInfo orderInfo, OrderDetail orderDetail, RequestOrderDetail requestOrderDetail, StoreVo storeVo, UserAddress userAddress) {
		orderInfo.setOrderSn(OrderUtil.getOrderSn());
		orderInfo.setUserId(orderDetail.getUserId());
		orderInfo.setStoreId(orderDetail.getStoreId());
		orderInfo.setStoreName(storeVo.getStoreName());
		orderInfo.setStoreProvince(storeVo.getProvince());
		orderInfo.setStoreCity(storeVo.getCity());
		orderInfo.setStoreArea(storeVo.getArea());
		orderInfo.setStoreAddress(storeVo.getAddress());
		orderInfo.setStoreLon(Double.valueOf(storeVo.getLon() != null ? storeVo.getLon() : "0.000000"));
		orderInfo.setStoreLat(Double.valueOf(storeVo.getLat() != null ? storeVo.getLat() : "0.000000"));
		orderInfo.setSettlementMan(storeVo.getSettlementMan());
		orderInfo.setSettlementAccount(storeVo.getSettlementAccount());
		orderInfo.setSettlementBank(storeVo.getSettlementBank());
		orderInfo.setPayType(requestOrderDetail.getPayType());
		orderInfo.setMemberDeliveryAddressId(requestOrderDetail.getMemberDeliveryAddressId());
		orderInfo.setDeliveryWay(requestOrderDetail.getDeliveryWay());
		orderInfo.setIsBill(requestOrderDetail.getIsBill());
		orderInfo.setBillType(requestOrderDetail.getBillType());
		orderInfo.setBillHeader(requestOrderDetail.getBillHeader());
		orderInfo.setTaxpayerNo(requestOrderDetail.getBillTaxpayerNo());
		orderInfo.setLinkMan(userAddress.getLinkMan());
		orderInfo.setMobile(userAddress.getMobile());
		orderInfo.setProvince(userAddress.getProvince());
		orderInfo.setCity(userAddress.getCity());
		orderInfo.setArea(userAddress.getArea());
		orderInfo.setStreet(userAddress.getStreet());
		orderInfo.setAddress(userAddress.getAddress());
		// orderInfo.setLon(lon);
		// orderInfo.setLat(lat);
		orderInfo.setRemark(requestOrderDetail.getRemark());
		orderInfo.setPointFee(0);
		orderInfo.setCommisionFee(0);
	}

	/** 以库存ID为索引获取订单商品信息集合 */
	protected void createInventoryMap(Map<Long, InventoryVo> inventoryMap, List<OrderDetail> orderDetailList) {
		if (CollectionUtils.isNotEmpty(orderDetailList)) {
			if (inventoryMap == null) {
				throw new NullPointerException();
			}
			Set<Long> inventoryIdSet = new HashSet<>();
			for (OrderDetail orderDetail : orderDetailList) {
				if (orderDetail.getInventoryId() == null) {
					continue;
				}
				inventoryIdSet.add(orderDetail.getInventoryId());
			}
			if (!inventoryIdSet.isEmpty()) {
				List<InventoryVo> inventoryList = orderDao.selectInventoryInId(inventoryIdSet);
				for (InventoryVo inventory : inventoryList) {
					if (inventory == null) {
						continue;
					}
					inventoryMap.put(inventory.getId(), inventory);
				}
			}
		}
	}

	/**
	 * 获取各种类型的订单数量
	 *
	 * @author 卫耀华
	 * @param userId
	 * @return
	 */
	@Override
	public ResponseOrderNum getOrderNum(Long userId) {
		// 售后订单数量
		int afterSalesOrderNum = 0;
		int num1 = afterSalesMapper.selectAfterSalesOrderNum1(userId);
		int num2 = afterSalesMapper.selectAfterSalesOrderNum2(userId);
		afterSalesOrderNum = num1 + num2;
		// 待付款订单
		int needToPayOrderNum = orderObjectMapper.selectNeedToPayOrderNum(userId);
		// 待发货
		int needToSendGoodsOrderNum = orderInfoMapper.selectNeedToSendGoodsOrderNum(userId);
		// 待收货
		int needToReceiveGoodsOrderNum = orderInfoMapper.selectNeedToReceiveGoodsOrderNum(userId);
		// 待评价
		int needToJudgeOfOrderNum = orderInfoMapper.selectNeedToJudgeOfOrderNum(userId);
		ResponseOrderNum resp = new ResponseOrderNum();
		resp.setNeedToPayOrderNum(needToPayOrderNum);
		resp.setNeedToSendGoodsOrderNum(needToSendGoodsOrderNum);
		resp.setNeedToReceiveGoodsOrderNum(needToReceiveGoodsOrderNum);
		resp.setNeedToJudgeOfOrderNum(needToJudgeOfOrderNum);
		resp.setAfterSalesOrderNum(afterSalesOrderNum);
		resp.setUserId(userId);
		return resp;
	}

	/**
	 * @Description: 获取我的店铺订单数量
	 * @Author: zhangrenjie
	 * @Date: 2018/1/22 9:39
	 *
	 */
	@Override
	public ResponseShopOrderNum getShopOrderNum(Long userId) {
		UserInfo userInfo = userInfoMapper.selectByUserId(userId);
		List<Long> userIds = new ArrayList<>();
		userIds.add(userId);
		List<User> uList = userService.getUserListByRecommendFrom(userInfo.getPersionId());//先获取我的下属用户ID
		if (!CollectionUtils.isEmpty(uList)) {
			for (User user : uList) {
				userIds.add(user.getId());
			}
		}
		// 售后订单数量
		//		int afterSalesOrderNum = 0;
		//		int num1 = afterSalesMapper.selectAfterSalesOrderNum1Batch(userIds);
		//		int num2 = afterSalesMapper.selectAfterSalesOrderNum2Batch(userIds);
		//		afterSalesOrderNum = num1 + num2;
		// 待付款订单
		int needToPayOrderNum = orderObjectMapper.selectNeedToPayOrderNumBatch(userIds);
		// 待发货
		int needToSendGoodsOrderNum = orderInfoMapper.selectNeedToSendGoodsOrderNumBatch(userIds);
		// 待收货
		int needToReceiveGoodsOrderNum = orderInfoMapper.selectNeedToReceiveGoodsOrderNumBatch(userIds);
		//已完成(状态为4和6)
		int finishedGoodsOrderNum = orderInfoMapper.selectfinishedGoodsOrderNumBatch(userIds);
		// 待评价
		//		int needToJudgeOfOrderNum = orderInfoMapper.selectNeedToJudgeOfOrderNumBatch(userIds);
		ResponseShopOrderNum resp = new ResponseShopOrderNum();
		resp.setNeedToPayOrderNum(needToPayOrderNum);
		resp.setNeedToSendGoodsOrderNum(needToSendGoodsOrderNum);
		resp.setNeedToReceiveGoodsOrderNum(needToReceiveGoodsOrderNum);
		resp.setFinishedGoodsOrderNum(finishedGoodsOrderNum);
		//		resp.setAfterSalesOrderNum(afterSalesOrderNum);
		resp.setUserId(userId);
		return resp;

	}

	/**
	 * @Description: 获取我的店铺订单数量（新--只查询我的店铺下的直接订单）
	 * @Author: zhangrenjie
	 * @Date: 2018/2/3 15:21
	 *
	 */
	@Override
	public ResponseShopOrderNum getShopOrderNumNew(Long userId) {
		ResponseShopOrderNum resp = new ResponseShopOrderNum();
		int finishedGoodsOrderNum = 0;//完成的订单包含状态4和6
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("userId", userId);
		String defaultTime = "2017-01-01";
		//加入默认时间筛选
		queryMap.put("startDate", defaultTime + " 00:00:00");
		queryMap.put("endDate", DateUtil.getFewDay(1) + " 00:00:00");
		//根据店中店Id查询各种状态下的订单数量
		List<Map<String, Object>> result = orderDetailMapper.selectStoreOrderNumByOpenStoreUserId(queryMap);
		for (Map<String, Object> stringObjectMap : result) {
			String status = stringObjectMap.get("status").toString();
			String statusNum = stringObjectMap.get("statusNum").toString();
			switch (status) {
				case "1":
					resp.setNeedToPayOrderNum(Integer.parseInt(statusNum));
					break;
				case "2":
					resp.setNeedToSendGoodsOrderNum(Integer.parseInt(statusNum));
					break;
				case "3":
					resp.setNeedToReceiveGoodsOrderNum(Integer.parseInt(statusNum));
					break;
				case "4":
					finishedGoodsOrderNum += (Integer.parseInt(statusNum));
					break;
				case "6":
					finishedGoodsOrderNum += (Integer.parseInt(statusNum));
					break;
				default:
			}
		}
		resp.setFinishedGoodsOrderNum(finishedGoodsOrderNum);
		resp.setUserId(userId);
		return resp;
	}

	/**
	 * 查询全部订单&状态 （1全部订单2待发货,3待收货，4待评价）
	 */
	@Override
	public List<OrderInfoVo> selectOrderInfoByStatusAndUserId(long userId, int status, int page, int pageSize) {
		//  Auto-generated method stub
		List<OrderInfoVo> listOrderInfoVo = new ArrayList<OrderInfoVo>();
		// 1是全部订单
		if (status == 1) {
			// 全部订单集合
			List<OrderInfo> listOrderInfo = orderInfoMapper.selectOrderInfoAllByUserId(userId, page, pageSize);
			// 遍历该订单集合
			for (OrderInfo OrderInfo : listOrderInfo) {
				// 循环查询订单详情
				List<OrderDetail> listOrderDetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(OrderInfo.getId());
				OrderInfoVo orderInfoVo = new OrderInfoVo();
				// 放入订单详情
				orderInfoVo.setListOrderDetail(listOrderDetail);
				orderInfoVo.setOrderInfoVo(OrderInfo);
				// 循环放入订单
				listOrderInfoVo.add(orderInfoVo);
			}
		}
		// 4为单独查询待评价 （待评价状态为订单已完成但是评价状态为0）
		if (status == 4) {
			List<OrderInfo> listOrderInfo = orderInfoMapper.selectOrderInfoStatusInfour(userId, page, pageSize);
			for (OrderInfo OrderInfo : listOrderInfo) {
				// 循环查询订单详情
				List<OrderDetail> listOrderDetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(OrderInfo.getId());
				OrderInfoVo orderInfoVo = new OrderInfoVo();
				// 放入订单详情
				orderInfoVo.setListOrderDetail(listOrderDetail);
				orderInfoVo.setOrderInfoVo(OrderInfo);
				// 循环放入订单
				listOrderInfoVo.add(orderInfoVo);
			}
		}
		if (status == 2 || status == 3) {
			// 2为待发货3为待收货
			List<OrderInfo> listOrderInfo = orderInfoMapper.selectOrderInfoByStatusAndUserId(userId, status, page, pageSize);
			for (OrderInfo OrderInfo : listOrderInfo) {
				// 循环查询订单详情
				List<OrderDetail> listOrderDetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(OrderInfo.getId());
				OrderInfoVo orderInfoVo = new OrderInfoVo();
				// 放入订单详情
				orderInfoVo.setListOrderDetail(listOrderDetail);
				orderInfoVo.setOrderInfoVo(OrderInfo);

				//实付总价放入订单头
				if (OrderInfo.getTotalFee() == 0) {//判断是否用现金
					orderInfoVo.setTotalFee(OrderInfo.getFreight());//运费就是总支付金额（实付总计）
				} else {
					orderInfoVo.setTotalFee(OrderInfo.getTotalFee());//支付金额已经包含运费（实付总计）
				}
				// 循环放入订单
				listOrderInfoVo.add(orderInfoVo);

			}
		}

		return listOrderInfoVo;
	}

	@Override
	public List<OrderInfoVo> listTalentOrderInfo(long userId, int status, int page, int pageSize) {
		//  Auto-generated method stub
		if (status == 1) {
			List<OrderInfoVo> orderInfoVoList = new ArrayList<OrderInfoVo>();
			List<Integer> Listinteger = commisionMapper.selectCommisionOrderInfoIdByUserId(userId, page, pageSize);
			for (int orderInfoId : Listinteger) {
				OrderInfo orderInfo = orderInfoMapper.selectOrderInfoAllById(orderInfoId);
				if (orderInfo == null) {
					continue;
				}
				List<OrderDetail> listOrderDetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(orderInfo.getId());
				OrderInfoVo orderInfoVo = new OrderInfoVo();
				orderInfoVo.setListOrderDetail(listOrderDetail);
				orderInfoVo.setOrderInfoVo(orderInfo);
				orderInfoVoList.add(orderInfoVo);
			}
			return orderInfoVoList;
		}
		List<OrderInfoVo> orderInfoVoList = new ArrayList<OrderInfoVo>();
		List<Integer> Listinteger = commisionMapper.selectCommisionOrderInfoIdByUserId(userId, page, pageSize);
		for (int orderInfoId : Listinteger) {
			OrderInfo orderInfo = orderInfoMapper.selectOrderInfoAllByIdAndStatus(orderInfoId, status);
			if (orderInfo == null) {
				continue;
			}
			List<OrderDetail> listOrderDetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(orderInfo.getId());
			OrderInfoVo orderInfoVo = new OrderInfoVo();
			orderInfoVo.setListOrderDetail(listOrderDetail);
			orderInfoVo.setOrderInfoVo(orderInfo);
			orderInfoVoList.add(orderInfoVo);
		}
		return orderInfoVoList;

	}

	@Override
	public OrderInfoVo getOrderInfoEntityByOrderSn(String orderSn, long userId) {
		//  Auto-generated method stub
		OrderInfoVo orderInfoVo = new OrderInfoVo();
		OrderInfo orderInfo = orderInfoMapper.selectOrderInfoEntityByOrderSn(orderSn);
		OrderObject orderObject = orderObjectMapper.selectByPrimaryKey(orderInfo.getOrderObjectId());
		orderInfoVo.setFreight(orderObject.getFreight());
		//		orderInfoVo.setTotalFee(orderInfo.getTotalFee()+orderObject.getFreight());
		//判断是否用现金支付
		if (orderInfo.getTotalFee() == 0) {
			orderInfoVo.setTotalFee(orderObject.getFreight());//运费就是总支付金额（实付总价）
		} else {
			orderInfoVo.setTotalFee(orderInfo.getTotalFee());//支付金额已经包含运费（实付总价）
		}
		//如果是别人看这个订单 收货人显示姓** 详细地址不展示
		if (userId > 0) {
			String linkMan = orderInfo.getLinkMan().substring(0, 1) + "**";
			String address = "*****";
			String mobile = orderInfo.getMobile().substring(0, 3) + "******" + orderInfo.getMobile().substring(9, 11);
			orderInfo.setLinkMan(linkMan);
			orderInfo.setAddress(address);
			orderInfo.setMobile(mobile);
		} else {
			orderInfo.setLinkMan(orderInfo.getLinkMan());
			orderInfo.setAddress(orderInfo.getAddress());
			orderInfo.setMobile(orderInfo.getMobile());
		}
		orderInfoVo.setOrderInfoVo(orderInfo);
		List<OrderDetail> listorderdetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(orderInfo.getId());
		List<OrderDetail> products = new ArrayList<OrderDetail>();//商品行
		List<OrderDetail> giftsProducts = new ArrayList<OrderDetail>();//赠品行
		for (OrderDetail orderDetail : listorderdetail) {
			if (orderDetail.getIsGift() == 0) {//商品行
				AfterSales afterSales = afterSalesMapper.selectAfterSalesByOrderDetailId(orderDetail.getId());
				if (afterSales != null) {
					if (orderDetail.getStatus() == 1 || orderDetail.getStatus() == 5 || orderDetail.getStatus() == 6 || orderDetail.getStatus() == 7 && afterSales.getType() == 2 && afterSales.getStatus() == 4) {
						orderDetail.setIsAfterSale(0);
					}
					if (orderDetail.getStatus() == 2 || orderDetail.getStatus() == 3 || orderDetail.getStatus() == 4) {
						orderDetail.setIsAfterSale(1);
					}
					Goods goods = goodsMapper.selectGoodsByIdTwo(orderDetail.getGoodId());
					// 返还现金币金额（总结算成本价*消费积分/100*商品数量）
					float returnCashMoney = (orderDetail.getTotalFee() + orderDetail.getCashCoin()) * (goods.getScoreRate() / (float) 100);
					orderDetail.setBacktrackCash(returnCashMoney);
					orderDetail.setAfterType(afterSales.getType());
					orderDetail.setAfterStatus(afterSales.getStatus());
					orderDetail.setAfterIsRefund(afterSales.getIsRefund());
					orderDetail.setAfterSalesId(afterSales.getId());
					orderDetail.setAfterType(afterSales.getType());
					orderDetail.setAfterStatus(afterSales.getStatus());
					orderDetail.setAfterIsRefund(afterSales.getIsRefund());
					orderDetail.setAfterSalesId(afterSales.getId());
					if (afterSales.getStatus() == 4) {
						if (afterSales.getType() == 1) {
							orderDetail.setAfterReason(afterSales.getStoreRefuseReason());
						} else {
							orderDetail.setAfterReason(afterSales.getStoreRefuseReason1());
						}
					}
				} else {
					if (orderDetail.getStatus() == 2 || orderDetail.getStatus() == 3 || orderDetail.getStatus() == 4) {
						orderDetail.setIsAfterSale(1);
						orderDetail.setAfterStatus(0);
						Goods goods = goodsMapper.selectGoodsByIdTwo(orderDetail.getGoodId());
						// 返还现金币金额（总结算成本价*消费积分/100*商品数量）
						float returnCashMoney = (orderDetail.getTotalFee() + orderDetail.getCashCoin()) * (goods.getScoreRate() / (float) 100);
						orderDetail.setBacktrackCash(returnCashMoney);
					}
				}
				products.add(orderDetail);
			} else {//赠品行（没有售后）
				orderDetail.setIsAfterSale(0);
				orderDetail.setAfterStatus(0);
				//				Goods goods = goodsMapper.selectGoodsByIdTwo(orderDetail.getGoodId());
				//				// 返还现金币金额（总结算成本价*消费积分/100*商品数量）
				//				float returnCashMoney = (orderDetail.getTotalFee() + orderDetail.getCashCoin())
				//						* (goods.getScoreRate() / (float) 100);
				//				orderDetail.setBacktrackCash(returnCashMoney);
				giftsProducts.add(orderDetail);
			}
		}
		//		orderInfoVo.setListOrderDetail(listorderdetail);
		orderInfoVo.setGiftsProducts(giftsProducts);
		orderInfoVo.setListOrderDetail(products);
		return orderInfoVo;
	}

	/**
	 * @Description: 获取订单详情（新）-针对Android客户端端特殊处理，并且兼容iOS客户端
	 * @Author: zhangrenjie
	 * @Date: 2018/1/15 15:04
	 *
	 */
	@Override
	public OrderInfoVo getOrderInfoEntityByOrderSnNew(RequestPageBaseModel requestPageBaseModel) {
		String orderSn = requestPageBaseModel.getOrderSn();
		long status = 0;//默认不隐藏
		if (requestPageBaseModel.getStatus() != null) {
			status = requestPageBaseModel.getStatus();
		}
		OrderInfoVo orderInfoVo = new OrderInfoVo();
		OrderInfo orderInfo = orderInfoMapper.selectOrderInfoEntityByOrderSn(orderSn);
		OrderObject orderObject = orderObjectMapper.selectByPrimaryKey(orderInfo.getOrderObjectId());
		orderInfoVo.setFreight(orderObject.getFreight());
		//		orderInfoVo.setTotalFee(orderInfo.getTotalFee()+orderObject.getFreight());
		//判断是否用现金支付
		if (orderInfo.getTotalFee() == 0) {
			orderInfoVo.setTotalFee(orderObject.getFreight());//运费就是总支付金额（实付总价）
		} else {
			orderInfoVo.setTotalFee(orderInfo.getTotalFee());//支付金额已经包含运费（实付总价）
		}
		//如果是别人看这个订单 收货人显示姓** 详细地址不展示,这里的参数status是针对Android客户端特殊处理
		//		if (requestPageBaseModel.getStatus() == null) {//IOS
		//			if (userId > 0) {
		//				String linkMan = orderInfo.getLinkMan().substring(0, 1) + "**";
		//				String address = "*****";
		//				String mobile = orderInfo.getMobile().substring(0, 3) + "******" + orderInfo.getMobile().substring(9, 11);
		//				orderInfo.setLinkMan(linkMan);
		//				orderInfo.setAddress(address);
		//				orderInfo.setMobile(mobile);
		//			}
		//		} else {//Android
		//			if (status == 1) {//隐藏
		//				String linkMan = orderInfo.getLinkMan().substring(0, 1) + "**";
		//				String address = "*****";
		//				String mobile = orderInfo.getMobile().substring(0, 3) + "******" + orderInfo.getMobile().substring(9, 11);
		//				orderInfo.setLinkMan(linkMan);
		//				orderInfo.setAddress(address);
		//				orderInfo.setMobile(mobile);
		//			}
		//		}
		/*if (requestPageBaseModel.getStatus() == null) {//IOS
			if (userId > 0) {
				String linkMan = orderInfo.getLinkMan().substring(0, 1) + "**";
				String address = "*****";
				String mobile = orderInfo.getMobile().substring(0, 3) + "******" + orderInfo.getMobile().substring(9, 11);
				orderInfo.setLinkMan(linkMan);
				orderInfo.setAddress(address);
				orderInfo.setMobile(mobile);
			}
		} else {//Android
			if (status == 1) {//隐藏
				String linkMan = orderInfo.getLinkMan().substring(0, 1) + "**";
				String address = "*****";
				String mobile = orderInfo.getMobile().substring(0, 3) + "******" + orderInfo.getMobile().substring(9, 11);
				orderInfo.setLinkMan(linkMan);
				orderInfo.setAddress(address);
				orderInfo.setMobile(mobile);
			}
		}*/
		//根据用户Id判断是否隐藏手机号码（自己的订单不隐藏）
		if (requestPageBaseModel.getUserId().intValue() == orderInfo.getUserId().intValue()) {
			orderInfo.setLinkMan(orderInfo.getLinkMan());
			orderInfo.setAddress(orderInfo.getAddress());
			orderInfo.setMobile(orderInfo.getMobile());
		} else {
			String linkMan = orderInfo.getLinkMan().substring(0, 1) + "**";
			String address = "*****";
			String mobile = orderInfo.getMobile().substring(0, 3) + "******" + orderInfo.getMobile().substring(9, 11);
			orderInfo.setLinkMan(linkMan);
			orderInfo.setAddress(address);
			orderInfo.setMobile(mobile);
		}
		orderInfoVo.setOrderInfoVo(orderInfo);
		List<OrderDetail> listorderdetail = orderDetailMapper.selectOrderDetailByOrderInfoIdC(orderInfo.getId());
		List<OrderDetail> products = new ArrayList<OrderDetail>();//商品行
		List<OrderDetail> giftsProducts = new ArrayList<OrderDetail>();//赠品行
		for (OrderDetail orderDetail : listorderdetail) {
			if (orderDetail.getIsGift() == 0) {//商品行
				AfterSales afterSales = afterSalesMapper.selectAfterSalesByOrderDetailId(orderDetail.getId());
				if (afterSales != null) {
					if (orderDetail.getStatus() == 1 || orderDetail.getStatus() == 5 || orderDetail.getStatus() == 6 || orderDetail.getStatus() == 7 && afterSales.getType() == 2 && afterSales.getStatus() == 4) {
						orderDetail.setIsAfterSale(0);
					}
					if (orderDetail.getStatus() == 2 || orderDetail.getStatus() == 3 || orderDetail.getStatus() == 4) {
						orderDetail.setIsAfterSale(1);
					}
					Goods goods = goodsMapper.selectGoodsByIdTwo(orderDetail.getGoodId());
					// 返还现金币金额（总结算成本价*消费积分/100*商品数量）
					float returnCashMoney = (orderDetail.getTotalFee() + orderDetail.getCashCoin()) * (goods.getScoreRate() / (float) 100);
					orderDetail.setBacktrackCash(returnCashMoney);
					orderDetail.setAfterType(afterSales.getType());
					orderDetail.setAfterStatus(afterSales.getStatus());
					orderDetail.setAfterIsRefund(afterSales.getIsRefund());
					orderDetail.setAfterSalesId(afterSales.getId());
					orderDetail.setAfterType(afterSales.getType());
					orderDetail.setAfterStatus(afterSales.getStatus());
					orderDetail.setAfterIsRefund(afterSales.getIsRefund());
					orderDetail.setAfterSalesId(afterSales.getId());
					if (afterSales.getStatus() == 4) {
						if (afterSales.getType() == 1) {
							orderDetail.setAfterReason(afterSales.getStoreRefuseReason());
						} else {
							orderDetail.setAfterReason(afterSales.getStoreRefuseReason1());
						}
					}
				} else {
					if (orderDetail.getStatus() == 2 || orderDetail.getStatus() == 3 || orderDetail.getStatus() == 4) {
						orderDetail.setIsAfterSale(1);
						orderDetail.setAfterStatus(0);
						Goods goods = goodsMapper.selectGoodsByIdTwo(orderDetail.getGoodId());
						// 返还现金币金额（总结算成本价*消费积分/100*商品数量）
						float returnCashMoney = (orderDetail.getTotalFee() + orderDetail.getCashCoin()) * (goods.getScoreRate() / (float) 100);
						orderDetail.setBacktrackCash(returnCashMoney);
					}
				}
				products.add(orderDetail);
			} else {//赠品行（没有售后）
				orderDetail.setIsAfterSale(0);
				orderDetail.setAfterStatus(0);
				//				Goods goods = goodsMapper.selectGoodsByIdTwo(orderDetail.getGoodId());
				//				// 返还现金币金额（总结算成本价*消费积分/100*商品数量）
				//				float returnCashMoney = (orderDetail.getTotalFee() + orderDetail.getCashCoin())
				//						* (goods.getScoreRate() / (float) 100);
				//				orderDetail.setBacktrackCash(returnCashMoney);
				giftsProducts.add(orderDetail);
			}
		}
		//		orderInfoVo.setListOrderDetail(listorderdetail);
		orderInfoVo.setGiftsProducts(giftsProducts);
		orderInfoVo.setListOrderDetail(products);
		//判断海外购商品
		for (OrderDetail OrderDetail : orderInfoVo.getListOrderDetail()) {
			GoodsExtends goodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(OrderDetail.getGoodId());
			if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1) {//有海外购产品
				orderInfoVo.setIsOverseasOrder(1);
				break;
			}
		}
		//如果有海外购商品 开店单 不允许售后
		if(orderInfoVo.getIsOverseasOrder()==1||orderObject.getOpenStore()==1) {
			for(OrderDetail orderDetail:orderInfoVo.getListOrderDetail()) {
				orderDetail.setAfterStatus(5);//ios版本隐藏掉
				orderInfoVo.setIsAfterSale(0);// android版本隐藏掉
			}
		}
		return orderInfoVo;
	}

	/**
	 * 取消订单
	 * @author gaoweiqi
	 * @date 2017年8月24日 12:44:05
	 */
	@Override
	public ResponseEntity<?> editCancelOrderByOrderId(Long orderObjectId, long userId) throws Exception {
		if (orderObjectId == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
		}
		int status_now = 5;
		final int status_old = 1;
		OrderObject orderObject = orderObjectMapper.selectByPrimaryKey(orderObjectId);
		if (orderObject == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
		}
		// 校验订单是否支付成功：支付成功的订单不允许直接取消，建议走售后流程
		List<OrderPay> orderPayList = this.orderPayService.selectAllByOrderSn(orderObject.getOrderSn());
		for (OrderPay orderPay : orderPayList) {
			if (orderPay.getStatus() == 1) {// 成功支付
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41008), HttpStatus.OK);
			} else {
				if (orderPay.getPayType() == 1) {// 微信支付
					// 调用微信接口查询是否支付成功
					String status = this.orderPayService.queryWechatPayOrderStatus(orderPay.getPaySn());
					if ("SUCCESS".equals(status.toUpperCase())) {// 支付成功
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41008), HttpStatus.OK);
					}
					logger.error("订单取消了,支付渠道：微信  ， 微信平台支付状态 :  {} , 订单号: {} , 支付单号: {} ", status, orderObject.getOrderSn(), orderPay.getPaySn());
				} else if (orderPay.getPayType() == 2) {// 支付宝支付
					// 调用支付宝接口查询是否支付成功
					String status = this.orderPayService.queryAliPayOrderStatus(orderPay.getPaySn());
					if ("TRADE_SUCCESS".equals(status.toUpperCase())) {// 支付成功
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41008), HttpStatus.OK);
					}
					logger.error("订单取消了,支付渠道：微信  ， 支付宝平台支付状态 :  {} , 订单号: {} , 支付单号: {} ", status, orderObject.getOrderSn(), orderPay.getPaySn());
				} else {// 易宝支付
					// 调用易宝接口查询是否支付成功
					String status = this.orderPayService.queryYeePayOrderStatus(orderPay.getPaySn());
					if ("SUCCESS".equals(status.toUpperCase())) {// 支付成功
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41008), HttpStatus.OK);
					}
					logger.error("订单取消了,支付渠道：易宝  ， 支付宝平台支付状态 :  {} , 订单号: {} , 支付单号: {} ", status, orderObject.getOrderSn(), orderPay.getPaySn());
				}
			}
		}
		if (orderObject.getStatus() == null || orderObject.getStatus() != 1) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20804), HttpStatus.OK);
		}
		if (orderObject.getUserId() != userId) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}

		if (new Date().getTime() - DateUtil.parse(orderObject.getCreateTime()).getTime() < 300000) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20803), HttpStatus.OK);
		}

		// 处理订单详情
		List<OrderDetail> detailList = orderDetailMapper.selectOrderDetilByOrderObjectId(orderObjectId);
		for (OrderDetail detail : detailList) {
			int updateOrderDetailStatus = orderDetailMapper.updateOrderDetailStatusById(detail.getId(), status_old, status_now, DateUtil.toString(new Date()));
			if (updateOrderDetailStatus != 1) {
				logger.error("------>订单详情操作异常{}", orderObject.getOrderSn());
				throw new PlatformException(ErrorEnum.C20804, "取消失败");
			}
			//归还库存
			if (detail.getInventoryId() != null && detail.getInventoryId() > 0) {
				inventoryMapper.updateReturnTheInventory(detail.getInventoryId(), detail.getQuantity());
			}
			//还原分时抢购库存
			if (detail.getLimitTimeSaleId() != null && detail.getLimitTimeSaleId() > 0) {
				int addNums = limitTimeSaleDetailMapper.updateAddSkuCount(detail.getLimitTimeSaleId(), detail.getGoodId(), detail.getProductId(), detail.getQuantity());
				if (addNums < 1) {
					logger.warn("------>订单还原分时抢购数异常{}-{}:{}-{}", orderObject.getOrderSn(), detail.getId(), detail.getLimitTimeSaleId(), detail.getLimitTimeSaleDetailId());
					//					throw new PlatformException(ErrorEnum.C20804, "取消失败");
				}
			}
			// 取消已经生成的结算信息
			int updateOrderSettlementStatus = orderSettlementMapper.updateOrderSettlementStatusByOrderDetailId(detail.getId());
			if (updateOrderSettlementStatus <= 0) {
				logger.warn("------>取消已生成的结算信息操作异常，没有结算信息{}", orderObject.getOrderSn());
				//				throw new PlatformException(ErrorEnum.C20804, "取消失败");
			}
			// 取消已经生成的消费积分
			//			int updatePointStatus =	pointTransactionMapper.updatePointStatusByOrderdetailId(detail.getId());
			//			if (updatePointStatus <= 0) {
			//				logger.error("------>取消消费积分信息失败，订单详情ID："+detail.getId());
			//			}
		}
		// 取消生成的运费分账信息
		if (orderObject.getFreight() != null && orderObject.getFreight() > 0) {
			List<OrderInfo> listInfo = orderInfoMapper.selectOrderInfoByOrderObjectIdC(orderObjectId);
			for (OrderInfo info : listInfo) {
				orderSettlementMapper.updateOrderSettlementStatusByOrderDetailId(-info.getId());
			}
		}
		// 处理子订单 处理父订单 将状态修改为5 交易关闭
		int orderInfoUpdateStatus = orderInfoMapper.updateOrderInfoStatusByOrderObjectId(orderObjectId, status_now, DateUtil.toString(new Date()));
		if (orderInfoUpdateStatus <= 0) {
			logger.error("------>子订单操作异常{}", orderObject.getOrderSn());
			throw new PlatformException(ErrorEnum.C20804, "取消失败");
		}
		int orderObjectUpdateStatus = orderObjectMapper.updateOrderObjectStatusById(orderObjectId, status_now, DateUtil.toString(new Date()));
		if (orderObjectUpdateStatus <= 0) {
			logger.error("------>父订单操作异常{}", orderObject.getOrderSn());
			throw new PlatformException(ErrorEnum.C20804, "取消失败");
		}

		// 归还已扣除的优惠券
		if (orderObject.getPromotionId() > 0) {
			if (1 != userPromotionMapper.updateStatusToReturnByUserId(orderObject.getPromotionId(), orderObject.getUserId())) {
				logger.error("------>归还优惠券操作异常{}-{}", orderObject.getOrderSn(), orderObject.getPromotionId());
				throw new PlatformException(ErrorEnum.C20804, "取消失败");
			}
		}

		if (orderObject.getCashCoin() > 0 || orderObject.getBalancePaid() > 0) {
			List<CUserMoneyChange> _add_user_money_change_list = new LinkedList<>();
			// 归还已扣除的现金币和余额付
			UserWalletVo userWallet = getUserWallet(orderObject.getUserId());
			if (orderObject.getCashCoin() > 0) {
				if (userWallet.getXzb().getFrozenQuantity() < orderObject.getCashCoin() || !userMoneyService.updateReleaseFreezeAmount(userWallet.getXzb().getId(), orderObject.getUserId(), orderObject.getCashCoin())) {
					logger.warn("订单[{}]冻结妆币[{}]不足以释放", orderObject.getId(), orderObject.getCashCoin());
					throw new PlatformException(ErrorEnum.C20125, "冻结妆币不足");
				}
				//封装钱包变动日志
				CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
				_add_user_money_change_list.add(addCUserMoneyChange);

				addCUserMoneyChange.setUserId(orderObject.getUserId());
				addCUserMoneyChange.setOrderSn(orderObject.getId());// 源ID
				addCUserMoneyChange.setExtend1(orderObject.getOrderSn());
				addCUserMoneyChange.setChangeAmount(orderObject.getCashCoin());
				addCUserMoneyChange.setNormalBeforAmount(userWallet.getXzb().getAvailQuantity());
				addCUserMoneyChange.setFreeBeforAmount(userWallet.getXzb().getFrozenQuantity());
				addCUserMoneyChange.setSourceType(Byte.valueOf("2"));// 积分
				addCUserMoneyChange.setChangeFreeAmount(-orderObject.getCashCoin());
			}
			if (orderObject.getBalancePaid() > 0) {
				if (userWallet.getBalance().getFrozenAmount() < orderObject.getBalancePaid() || !userMoneyService.updateReleaseFreezeAmount(userWallet.getBalance().getId(), orderObject.getUserId(), orderObject.getBalancePaid())) {
					logger.warn("订单[{}]冻结余额[{}]不足以释放", orderObject.getId(), orderObject.getBalancePaid());
					throw new PlatformException(ErrorEnum.C20125, "冻结余额不足");
				}
				//封装钱包变动日志
				CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
				_add_user_money_change_list.add(addCUserMoneyChange);

				addCUserMoneyChange.setUserId(orderObject.getUserId());
				addCUserMoneyChange.setOrderSn(orderObject.getId());// 源ID
				addCUserMoneyChange.setExtend1(orderObject.getOrderSn());
				addCUserMoneyChange.setChangeAmount(orderObject.getBalancePaid());
				addCUserMoneyChange.setNormalBeforAmount(userWallet.getBalance().getNormalAmount());
				addCUserMoneyChange.setFreeBeforAmount(userWallet.getBalance().getFrozenAmount());
				addCUserMoneyChange.setSourceType(Byte.valueOf("1"));// 余额
				addCUserMoneyChange.setChangeFreeAmount(-orderObject.getBalancePaid());
			}
			//记录变化日志
			saveUserMoneyChange(orderObject.getUserId(), _add_user_money_change_list);
		}
		if (orderObject.getRedPacketOwnerId() != null && orderObject.getRedPacketOwnerId() > 0) {
			BackRedPacketRequest request = new BackRedPacketRequest();
			request.setBackType(RedPacketBackTypeEnum.NOT_PAY.getType());
			request.setRedPacketOwnerId(orderObject.getRedPacketOwnerId());
			if (!redPacketBiz.backRedPacket(request)) {
				logger.error("待支付订单[{}-{}]自动取消归还兔币[{}-{}]失败", orderObject.getId(), orderObject.getOrderSn(), orderObject.getRedPacketId(), orderObject.getRedPacketOwnerId());
				throw new PlatformException(ErrorEnum.C20804, "归还兔币失败");
			}
		}
		//		int updateMoneyStatus = userMoneyService.refundUserMoneyAndPointByorderObjectID(orderObject.getUserId(), orderObject.getCashCoin(), 15, orderObject.getBalancePaid(), 6, orderObject.getId());
		//		if (updateMoneyStatus <= 0) {
		//			logger.error("------>归还已扣除的现金币和余额付异常");
		//		}
		// 取消已经生成的分佣
		//		int updateCommisionStatus = commisionMapper.updateCommisionStatusByOrderObjectId(orderObject.getId());
		//		if (updateCommisionStatus <= 0) {
		//			logger.error("------>取消已生成的分佣操作异常，没有分佣信息{}", orderObject.getOrderSn());
		//		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	/**
	 * <dl>
	 * <dt>记录用户钱包变动日志</dt>
	 * </dl>
	 * @param userId 用户ID
	 * @param addUserMoneyChangeList 变动日志集合
	 * @author zls
	 * @date 2017年9月6日 下午3:40:10
	 */
	protected void saveUserMoneyChange(Long userId, List<CUserMoneyChange> addUserMoneyChangeList) {
		UserWalletVo userWallet = getUserWallet(userId);
		for (CUserMoneyChange addCUserMoneyChange : addUserMoneyChangeList) {
			switch (addCUserMoneyChange.getSourceType()) {
				case 1://余额
					addCUserMoneyChange.setExtend2(userWallet.getBalance().getId() + "");
					addCUserMoneyChange.setNormalAfterAmount(userWallet.getBalance().getNormalAmount());
					addCUserMoneyChange.setFreeAfterAmount(userWallet.getBalance().getFrozenAmount());
					break;
				case 2://妆币
					addCUserMoneyChange.setExtend2(userWallet.getXzb().getId() + "");
					addCUserMoneyChange.setNormalAfterAmount(userWallet.getXzb().getAvailQuantity());
					addCUserMoneyChange.setFreeAfterAmount(userWallet.getXzb().getFrozenQuantity());
					break;

				default:
					throw new NullPointerException("变动日志类型为空");
			}
			userMoneyChangeMapper.insertSelective(addCUserMoneyChange);
		}
	}

	@Override
	public List<OrderObject> selectOrderObjectForCommision() {
		//  Auto-generated method stub
		return orderDao.selectOrderObjectForCommision();
	}
	@Override
	public List<Map<String, Object>> selectOrderObjectCommision(String OrderDetailIds) {
		List<String> ids = StringUtil.spiltString(OrderDetailIds, ",");
		List<Map<String, Object>> listMap=new ArrayList<Map<String, Object>>();
		try {
			for (String StrId : ids) {
				Long OrderDetailId = Long.parseLong(StrId);
				OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(OrderDetailId);
				OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderDetail.getOrderId());
				OrderObject obj = orderObjectMapper.selectByPrimaryKey(orderDetail.getOrderObjectId());
				Map<String, Object> resultMap = new HashMap<String, Object>();
				if (obj == null) {
					resultMap.put("OrderDetailId", OrderDetailId);
					resultMap.put("message", "数据偷渡到火星了，请联系客服遣返");
					continue;
				}
				resultMap.put("OrderDetailId", OrderDetailId);
				switch (obj.getStatus().intValue()) {
				case 1:
					resultMap.put("message", "订单还没有支付哦");
					break;
				case 2:
					resultMap.put("message", "订单还没有发货哦");
					break;
				case 3:
					if (StringUtils.isNotBlank(orderInfo.getSendTime())) {
						String time = DateUtils.addDay(DateUtil.parse(orderInfo.getSendTime(), BaseConstants.DATE_FORMAT_YYYY_MM_DD), 14, BaseConstants.DATE_FORMAT_YYYY_MM_DD);
						resultMap.put("message", "订单还没有确认收货，预计系统自动确认收货时间：" + time);
					} else {
						resultMap.put("message", "赶快去确认收货吧！");
					}
					break;
				case 4:
					StringBuffer buffer = new StringBuffer();
					buffer.append("订单未评价，预计系统自动完成订单时间:").append(DateUtils.addDay(DateUtil.parse(obj.getUpdateTime(), BaseConstants.DATE_FORMAT_YYYY_MM_DD), 7 + obj.getRefundStartTime() / 60 / 24 + 1, BaseConstants.DATE_FORMAT_YYYY_MM_DD));
					if ((obj.getRefundStartTime() / 60 / 24) > 1) {
						buffer.append(" 计算规则：订单更新时间：").append(DateUtils.format(DateUtil.parse(obj.getUpdateTime(), BaseConstants.DATE_FORMAT_YYYY_MM_DD), BaseConstants.DATE_FORMAT_YYYY_MM_DD)).append(" + ");
						buffer.append(obj.getRefundStartTime() / 60 / 24).append("天(售后单累计耗时)+");
						buffer.append(" 8天").append(("系统自动完成订单耗时)"));
					} else {
						buffer.append(" 计算规则：订单更新时间：").append(DateUtils.format(DateUtil.parse(obj.getUpdateTime(), BaseConstants.DATE_FORMAT_YYYY_MM_DD), BaseConstants.DATE_FORMAT_YYYY_MM_DD)).append("+ ");
						buffer.append(" 8天").append("(系统自动完成订单耗时)");
					}
					resultMap.put("message", buffer.toString());
					break;
				case 5:
					resultMap.put("message", "订单已取消");
					break;
				case 6:
					resultMap.put("message", "订单已完成，完成时间：" + (DateUtils.format(DateUtil.parse(obj.getUpdateTime(), BaseConstants.DATE_FORMAT_YYYY_MM_DD), BaseConstants.DATE_FORMAT_YYYY_MM_DD)));
					break;
				case 7:
					resultMap.put("message", "订单已关闭");
					break;
				default:
					resultMap.put("message", "");
				}
				listMap.add(resultMap);
			}

		} catch (Exception e) {
			logger.error("订单查询失败：{}", e.getMessage());
		}
		return listMap;
	}

	@Override
	public List<Commision> selectByOrderObjectIdForCommision(long orderDetailId) {
		//  Auto-generated method stub
		return orderDao.selectByOrderObjectIdForCommision(orderDetailId);
	}

	@Override
	public List<Commision> selectInOrderObjectIdForCommision(List<OrderObject> orderObjectList) {
		//  Auto-generated method stub
		return orderDao.selectInOrderObjectIdForCommision(orderObjectList);
	}

	@Override
	public List<CUserPointTransaction> selectInOrderObjectIdForPoint(List<OrderObject> orderObjectList) {
		//  Auto-generated method stub
		List<Long> IDList = new ArrayList<Long>();
		for (OrderObject obj : orderObjectList) {
			IDList.add(obj.getId());
		}
		if (IDList.size() > 0) {
			return userPointTransactionMapper.selectInOrderObjectIdForPointTransaction(IDList);
		} else {
			return null;
		}
	}

	@Override
	public List<OrderInfo> selectOrderInfoInOOIdForCommision(List<OrderObject> orderObjectList) {
		//  Auto-generated method stub
		return orderDao.selectOrderInfoInOOIdForCommision(orderObjectList);
	}

	@Override
	public void autoCommision(List<Commision> commisionList, List<UserJournal> userJournalList, List<CUserPointTransaction> pointTransactionList, List<UserPointJournal> userPointJournalList, List<OrderObject> orderObjectList) throws PlatformException {
		try {
			int ujResult = 0;
			//保存余额事务流水，更新用户余额
			for (UserJournal userJournal : userJournalList) {
				//保存分佣流水
				ujResult = userJournalService.insertUserJournal(userJournal);
				//查找处理后的流水
				UserJournal userJournalTemp = null;
				userJournalTemp = userJournalService.getUserJournalByBusinessTypeAndCommisionID(userJournal.getBusinessTypeId(), userJournal.getCommisionId());
				if (userJournalTemp != null && userJournal.getUserId() == userJournalTemp.getUserId()) {//处理账户余额
					UserMoney userAmount = userMoneyMapper.selectByTypeIDAndUserID(userJournalTemp.getUserId(), 1);// 账户余额
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(userJournalTemp.getUserId());
					MoneyChange.setOrderSn((long) userJournalTemp.getId());// 源ID
					MoneyChange.setChangeAmount(userJournalTemp.getMoney());
					MoneyChange.setNormalBeforAmount(userAmount.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userAmount.getNormalAmount() + userJournalTemp.getMoney());
					MoneyChange.setSourceType(Byte.valueOf("1"));//余额
					ujResult = moneyChangeMapper.insertSelective(MoneyChange);
					if (ujResult != 1) {
						throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
					}
					// 增加账户余额
					ujResult = userMoneyMapper.increaseUserAmount(userJournalTemp.getUserId(), 1, userJournalTemp.getMoney());
					if (ujResult != 1) {
						throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
					}
				}
			}
			for (UserPointJournal userPointJournal : userPointJournalList) {
				UserMoney userPoint = userMoneyMapper.selectByTypeIDAndUserID(userPointJournal.getUserId(), 2);// 账户积分
				//保存妆币流水
				userPointJournalMapper.insertSelective(userPointJournal);
				//查找处理后的流水
				UserPointJournal userPointJournalTemp = null;
				userPointJournalTemp = userPointJournalMapper.selectBySourceIDAndBusinessType(userPointJournal.getBusinessSourceId(), userPointJournal.getBusinessTypeId());
				if (userPointJournalTemp != null && (userPointJournalTemp.getUserId().intValue() == userPointJournal.getUserId().intValue())) {//查到对应的处理记录了
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(userPointJournalTemp.getUserId());
					MoneyChange.setOrderSn(userPointJournalTemp.getId());// 源ID
					MoneyChange.setChangeAmount(userPointJournalTemp.getAmount().intValue());
					MoneyChange.setNormalBeforAmount(userPoint.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userPoint.getNormalAmount() + userPointJournalTemp.getAmount().intValue());
					MoneyChange.setSourceType(Byte.valueOf("2"));// 积分
					ujResult = moneyChangeMapper.insertSelective(MoneyChange);
					if (ujResult != 1) {
						throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
					}
					// 增加账户妆币
					ujResult = userMoneyMapper.increaseUserAmount(userPointJournalTemp.getUserId(), 2, userPointJournalTemp.getAmount());
					if (ujResult != 1) {
						throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
					}
				}
			}
			int crResult = 0;
			//更新余额事务为已处理
			if (commisionList != null && commisionList.size() > 0) {
				crResult = orderDao.updateCommisionResultInId(commisionList, DateUtil.getNow());
				if (crResult < 1) {
					throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
				}
			}
			if (pointTransactionList != null && pointTransactionList.size() > 0) {
				//更新积分事务为已处理
				crResult = userPointTransactionMapper.updateCommisionResultInId(pointTransactionList);
				if (crResult < 1) {
					throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
				}
			}
			//更新订单明细状态为交易成功
			int osResult = orderDao.updateOrderDetailStatusInOrderObjectId(orderObjectList);
			if (osResult < 1) {
				throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
			}
			//更新订单状态为交易成功
			int oisResult = orderDao.updateOrderInfoStatusInOrderObjectId(orderObjectList);
			if (oisResult < 1) {
				throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
			}
			//更新交易单状态为交易已成功
			int oosResult = orderDao.updateOrderObjectStatusInId(orderObjectList);
			if (oosResult < 1) {
				throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
	}

	public void autoCommision(List<Commision> commisionList, List<UserJournal> userJournalList) throws PlatformException {
		try {
			int ujResult = 0;
			//保存余额事务流水，更新用户余额
			for (UserJournal userJournal : userJournalList) {
				//保存分佣流水
				ujResult = userJournalService.insertUserJournal(userJournal);
				//查找处理后的流水
				UserJournal userJournalTemp = null;
				userJournalTemp = userJournalService.getUserJournalByBusinessTypeAndCommisionID(userJournal.getBusinessTypeId(), userJournal.getCommisionId());
				if (userJournalTemp != null && userJournal.getUserId() == userJournalTemp.getUserId()) {//处理账户余额
					UserMoney userAmount = userMoneyMapper.selectByTypeIDAndUserID(userJournalTemp.getUserId(), 1);// 账户余额
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(userJournalTemp.getUserId());
					MoneyChange.setOrderSn((long) userJournalTemp.getId());// 源ID
					MoneyChange.setChangeAmount(userJournalTemp.getMoney());
					MoneyChange.setNormalBeforAmount(userAmount.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userAmount.getNormalAmount() + userJournalTemp.getMoney());
					MoneyChange.setSourceType(Byte.valueOf("1"));//余额
					ujResult = moneyChangeMapper.insertSelective(MoneyChange);
					if (ujResult != 1) {
						throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
					}
					// 增加账户余额
					ujResult = userMoneyMapper.increaseUserAmount(userJournalTemp.getUserId(), 1, userJournalTemp.getMoney());
					if (ujResult != 1) {
						throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
					}
				}
			}
			int crResult = 0;
			//更新余额事务为已处理
			if (commisionList != null && commisionList.size() > 0) {
				crResult = orderDao.updateCommisionResultInId(commisionList, DateUtil.getNow());
				if (crResult < 1) {
					throw new PlatformException(ErrorEnum.C20801, ErrorEnum.C20801.getMessage());
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
	}

	@Override
	public List<OrderSettlementVo> selectByOrderSnForSettlement(String orderSn) {
		return orderDao.selectByOrderSnForSettlement(orderSn);
	}

	@Override
	public List<OrderSettlementVo> selectByOrderSnForFreightSettlement(String orderSn) {
		return orderDao.selectByOrderSnForFreightSettlement(orderSn);
	}

	@Override
	public List<OrderSettlementVo> selectByOrderSnForSettlementDetail(String orderSn) {
		return orderDao.selectByOrderSnForSettlementDetail(orderSn);
	}

	@Override
	public int updateSettlementStatusByID(Long ID, int status, String settlementNo, String companyAccount, String managerAccount, int selfSupport) {
		return orderDao.updateSettlementStatusByID(ID, status, settlementNo, companyAccount, managerAccount, selfSupport);
	}

	@Override
	public int updateStatusBySettlementId(Long settlementId, int status, String settlementNo, String companyAccount, String managerAccount) {
		return orderDao.updateStatusBySettlementId(settlementId, status, settlementNo, companyAccount, managerAccount);
	}

	@Override
	public int updateSettlementStatusByOrderSn(String orderSn, int status, String settlementNo) {
		return orderDao.updateSettlementStatusByOrderSn(orderSn, status, settlementNo);
	}

	@Override
	public OrderObject selectOrderObjectByOrderSn(String orderSn) {
		//  Auto-generated method stub
		return orderDao.selectOrderObjectByOrderSn(orderSn);
	}

	@Override
	public void updatePayOrderInfo(String orderSn, int payType, int paymentFee, String payId) throws PlatformException {
		//  自动生成的方法存根
		OrderObject orderObject = orderDao.selectOrderObjectByOrderSn(orderSn);
		if (orderObject == null) {
			throw new PlatformException(ErrorEnum.C21202, ErrorEnum.C21202.getMessage() + "(" + orderSn + ")");
		}
		if (payType == 0) {
			payType = orderObject.getPayType();
		}
		int procedureFee = 0;//手续费
		// 支付方式 0位空 2为支付宝支付 支付宝支付没有手续费
		if (payType != 0 && (payType == PayTypeEnum.T1.getCode().intValue() || payType == PayTypeEnum.T3.getCode().intValue())) {
			// 支付金额 * 千分之六
			procedureFee = paymentFee * 6 / 1000;
		}
		int bankIn = paymentFee - procedureFee;//银行实收
		String payTime = DateUtil.getNow();//老接口未获取实际支付时间
		//更新交易订单支付信息
		int updateOrderObject = orderDao.updateOrderObjectPay(orderObject.getId(), bankIn, procedureFee, payType, paymentFee, payId, payTime);
		if (updateOrderObject <= 0) {
			throw new PlatformException(ErrorEnum.C21203, ErrorEnum.C21203.getMessage());
		}
		//更新订单支付信息（目前值更新了订单状态为2）
		int updateOrderInfo = orderDao.updateOrderInfoPayByOrderObjectId(orderObject.getId(), 0, 0, payType, 0, payId, payTime);
		if (updateOrderInfo <= 0) {
			throw new PlatformException(ErrorEnum.C21203, ErrorEnum.C21203.getMessage());
		}
		//更新订单明细状态信息
		int updateOrderDetail = orderDao.updateOrderDetailPayByOrderObjectId(orderObject.getId());
		if (updateOrderDetail <= 0) {
			throw new PlatformException(ErrorEnum.C21203, ErrorEnum.C21203.getMessage());
		}
		// 处理积分、余额、佣金业务
		//		this.excuteUserMoney(orderObject);
		//更新开店单信息（主要更新购买人身份信息）
		//		updateOpenStore(orderObject);
		// 修改支付记录的状态  0->1
		OrderPay orderPay = this.orderPayMapper.selectByExternalId(payId);
		if (orderPay == null) {
			throw new PlatformException(ErrorEnum.C41007, ErrorEnum.C41007.getMessage());
		}
		int n = this.orderPayMapper.effectByPaySn(orderPay.getPaySn(), DateUtil.getNow());
		if (n <= 0) {
			throw new PlatformException(ErrorEnum.C41006, ErrorEnum.C41006.getMessage());
		}
		//处理分佣结算单
		OrderSettlementCommision orderSettlementCommision = orderSettlementCommisionMapper.selectByorderSn(orderSn);
		orderSettlementCommisionMapper.updateStatus("消息队列任务", 3, 1, DateUtil.getNow(), orderSettlementCommision.getId());

		ResponseUser buyUser = userService.selectUserRoleById(orderObject.getUserId());
		if (buyUser != null) {
			//支付成功发送短信
			sendSuccessOrderPaymentSms(orderSn, buyUser.getUserName(), paymentFee);
			//发送兔币
			sendRedPacketByPayment(orderSn, orderObject.getOpenStore() == 1, buyUser, orderObject.getOpenStoreUserId());
		}
		if (orderObject.getRedPacketId() > 0) {
			boolean consumeRedPacket = false;
			ConsumeRedPacketRequest consumeRedPacketRequest = new ConsumeRedPacketRequest();
			try {
				consumeRedPacketRequest.setRedPacketOwnerId(orderObject.getRedPacketOwnerId());
				consumeRedPacketRequest.setUserId(orderObject.getUserId().intValue());
				consumeRedPacketRequest.setConsumeType(1);
				consumeRedPacket = redPacketBiz.consumeRedPacket(consumeRedPacketRequest);
			} catch (Exception e) {
				logger.error("用户[{}]的兔币[{}-{}]不可用", orderObject.getUserId(), orderObject.getRedPacketId(), orderObject.getRedPacketOwnerId());
				throw new PlatformException(ErrorEnum.C30110, "兔币不可用");
			}
			if (!consumeRedPacket) {
				logger.error("用户[{}]的兔币[{}-{}]不可用", orderObject.getUserId(), orderObject.getRedPacketId(), orderObject.getRedPacketOwnerId());
				throw new PlatformException(ErrorEnum.C30110, "兔币不可用");
			}
			consumeRedPacketRequest = null;
		}
	}

	protected void warnLog(ReqHeaderVo reqHeader, String msg, Object... objects) {
		logger.warn(msg + " [渠道{}-版本{}]", ArrayUtils.addAll(objects, reqHeader.getPhoneType(), reqHeader.getAppSystemVersion()));
	}

	protected void errorLog(ReqHeaderVo reqHeader, String msg, Object... objects) {
		logger.error(msg + "[渠道{}-版本{}] ", ArrayUtils.addAll(objects, reqHeader.getPhoneType(), reqHeader.getAppSystemVersion()));
	}

	@Override
	public void updatePayOrderInfo(String orderSn, OrderPay orderPay, long paymentFee, String payId) throws PlatformException {
		OrderObject orderObject = orderDao.selectOrderObjectByOrderSn(orderSn);
		if (orderObject == null) {
			throw new PlatformException(ErrorEnum.C21202, ErrorEnum.C21202.getMessage() + "(" + orderSn + ")");
		}
		if (orderObject.getStatus().intValue() != 1) {
			throw new PlatformException("订单状态不符，已被更改" + orderObject.getStatus());
		}
		long procedureFee = 0;//手续费
		// 支付方式 0位空 2为支付宝支付 支付宝支付没有手续费
		if (orderPay.getPayType() != 0 && (orderPay.getPayType() == PayTypeEnum.T1.getCode().intValue() || orderPay.getPayType() == PayTypeEnum.T3.getCode().intValue())) {
			// 支付金额 * 千分之六
			procedureFee = paymentFee * 6 / 1000;
		}
		long bankIn = paymentFee - procedureFee;//银行实收
		//更新交易订单支付信息
		int updateOrderObject = orderDao.updateOrderObjectPay(orderObject.getId(), bankIn, procedureFee, orderPay.getPayType(), paymentFee, payId, orderPay.getPayTime());
		if (updateOrderObject <= 0) {
			throw new PlatformException(ErrorEnum.C21203, ErrorEnum.C21203.getMessage());
		}
		//更新订单支付信息（目前值更新了订单状态为2）
		int updateOrderInfo = orderDao.updateOrderInfoPayByOrderObjectId(orderObject.getId(), 0, 0, orderPay.getPayType(), 0, payId, orderPay.getPayTime());
		if (updateOrderInfo <= 0) {
			throw new PlatformException(ErrorEnum.C21203, ErrorEnum.C21203.getMessage());
		}
		//更新订单明细状态信息
		int updateOrderDetail = orderDao.updateOrderDetailPayByOrderObjectId(orderObject.getId());
		if (updateOrderDetail <= 0) {
			throw new PlatformException(ErrorEnum.C21203, ErrorEnum.C21203.getMessage());
		}
		// 处理积分、余额、佣金业务
		//		this.excuteUserMoney(orderObject);
		//更新开店单信息（主要更新购买人身份信息）
		//		updateOpenStore(orderObject);
		if (!orderPayService.modifOk(orderPay.getId(), payId, orderPay.getPayTime())) {
			throw new PlatformException(ErrorEnum.C41006, ErrorEnum.C41006.getMessage());
		}
		OrderSettlementCommision orderSettlementCommision = orderSettlementCommisionMapper.selectByorderSn(orderSn);
		orderSettlementCommisionMapper.updateStatus("消息队列任务", 3, 1, DateUtil.getNow(), orderSettlementCommision.getId());

		ResponseUser buyUser = userService.selectUserRoleById(orderObject.getUserId());
		if (buyUser != null) {
			//支付成功发送短信
			sendSuccessOrderPaymentSms(orderSn, buyUser.getUserName(), paymentFee);
			//发送兔币
			sendRedPacketByPayment(orderSn, orderObject.getOpenStore() == 1, buyUser, orderObject.getOpenStoreUserId());
		}
		if (orderObject.getRedPacketId() > 0) {
			boolean consumeRedPacket = false;
			ConsumeRedPacketRequest consumeRedPacketRequest = new ConsumeRedPacketRequest();
			try {
				consumeRedPacketRequest.setRedPacketOwnerId(orderObject.getRedPacketOwnerId());
				consumeRedPacketRequest.setUserId(orderObject.getUserId().intValue());
				consumeRedPacketRequest.setConsumeType(1);
				consumeRedPacket = redPacketBiz.consumeRedPacket(consumeRedPacketRequest);
			} catch (Exception e) {
				logger.error("用户[{}]的兔币[{}-{}]不可用", orderObject.getUserId(), orderObject.getRedPacketId(), orderObject.getRedPacketOwnerId());
				throw new PlatformException(ErrorEnum.C30110, "兔币不可用");
			}
			if (!consumeRedPacket) {
				logger.error("用户[{}]的兔币[{}-{}]不可用", orderObject.getUserId(), orderObject.getRedPacketId(), orderObject.getRedPacketOwnerId());
				throw new PlatformException(ErrorEnum.C30110, "兔币不可用");
			}
			consumeRedPacketRequest = null;
		}
	}

	/** 支付成功发送短信 */
	protected void sendSuccessOrderPaymentSms(String orderSn, String mobile, long paymentFee) {
		try {
			SMSSuccessOrderPayment smsSuccessOrderPayment = new SMSSuccessOrderPayment(mobile);
			smsSuccessOrderPayment.setOrderSn(orderSn);
			smsSuccessOrderPayment.setPayTime(DateUtil.getNow());
			smsSuccessOrderPayment.setPayAmount(NumberUtil.getFloatPrice(paymentFee));
			smsService.successOrderPayment(smsSuccessOrderPayment);
		} catch (Exception e) {
			logger.error("发送订单支付成功短信失败：{}", e.getMessage(), e);
		}
	}

	/** 支付送兔币 */
	protected void sendRedPacketByPayment(String orderSn, boolean isOpenStoreOrder, ResponseUser buyUser, Long storeUserId) {
		if (buyUser == null || buyUser.getUserId() == null || buyUser.getUserId() < 1) {
			logger.warn("订单[{}]下单人为空，不处理送兔币业务", orderSn);
			return;
		}
		sendFirstOrderRedPacket(orderSn, buyUser.isStoreLevel(), isOpenStoreOrder, buyUser.getUserId(), storeUserId);
		sendOpenStoreRedPacket(orderSn, isOpenStoreOrder, buyUser.getUserId(), storeUserId);
		sendShareLiveOrderPacket(orderSn,buyUser.getUserId(),storeUserId);
	}
	
	/*** 发送直播间分享下单兔币 **/
	public void sendShareLiveOrderPacket(String orderSn,Long buyUserId, Long storeUserId) {
		OrderObject _orderObject = orderObjectMapper.selectByOrderSn(orderSn);
		if(_orderObject != null && _orderObject.getOpenStore() == 0) {
			//List<LiveOrder> _liveOrderList = liveOrderService.selectLiveOrderByOrderOrderObjectId(_orderObject.getId());
			if(StringUtils.equals(CommonConstants.PHONE_CLIENT_WX, _orderObject.getPayClientSource())) {
				
				if(_orderObject.getUserId() == _orderObject.getOpenStoreUserId()) {//自己从自己店里面买，只会享受一次活动（发给下单人）
					//直播间产生的订单给下单人赠送兔币
					try {
						GiveRedPacketByEventRequest request = new GiveRedPacketByEventRequest();
						request.setEventType(RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType());
						request.setCreateTime(new Date());
						request.setInvitationUserId(storeUserId.intValue());//邀请人
						request.setReceiveUserId(buyUserId.intValue());//接收人
						boolean giveRedPacketByEventType = redPacketBiz.giveRedPacketByEventType(request);
						if (!giveRedPacketByEventType) {
							logger.error("微商城订单[{}]赠送下单人[{}-->{}]兔币[{}-{}]失败", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getDesc());
						} else {
							logger.warn("微商城订单[{}]赠送下单人[{}-->{}]兔币[{}-{}]", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getDesc());
						}
					}catch(Exception e) {
						logger.error("微商城订单[{}]赠送下单人[{}-->{}]兔币[{}-{}]异常：{}", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getDesc(), e.getMessage(), e);
					}
					
					
				}else{
					//直播间产生的订单给下单人赠送兔币
					try {
						GiveRedPacketByEventRequest request = new GiveRedPacketByEventRequest();
						request.setEventType(RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType());
						request.setCreateTime(new Date());
						request.setInvitationUserId(storeUserId.intValue());//邀请人
						request.setReceiveUserId(buyUserId.intValue());//接收人
						boolean giveRedPacketByEventType = redPacketBiz.giveRedPacketByEventType(request);
						if (!giveRedPacketByEventType) {
							logger.error("微商城订单[{}]赠送下单人[{}-->{}]兔币[{}-{}]失败", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getDesc());
						} else {
							logger.warn("微商城订单[{}]赠送下单人[{}-->{}]兔币[{}-{}]", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getDesc());
						}
					}catch(Exception e) {
						logger.error("微商城订单[{}]赠送下单人[{}-->{}]兔币[{}-{}]异常：{}", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_USER_AWARD.getDesc(), e.getMessage(), e);
					}
					
					//直播间产生的订单给店主赠送兔币
					try {
						GiveRedPacketByEventRequest request = new GiveRedPacketByEventRequest();
						request.setEventType(RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getType());
						request.setCreateTime(new Date());
						request.setInvitationUserId(storeUserId.intValue());//邀请人
						request.setReceiveUserId(storeUserId.intValue());//接收人
						boolean giveRedPacketByEventType = redPacketBiz.giveRedPacketByEventType(request);
						if (!giveRedPacketByEventType) {
							logger.error("微商城订单[{}]赠送店主[{}-->{}]兔币[{}-{}]失败", orderSn, storeUserId, storeUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getDesc());
						} else {
							logger.warn("微商城订单[{}]赠送店主[{}-->{}]兔币[{}-{}]", orderSn, storeUserId, storeUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getDesc());
						}
					}catch(Exception e) {
						logger.error("微商城订单[{}]赠送店主[{}-->{}]兔币[{}-{}]异常：{}", orderSn, storeUserId, storeUserId, RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getType(), RedPacketEventTypeEnum.SHARE_PRODUCT_LIVE_ORDER_STORE_AWARD.getDesc(), e.getMessage(), e);
					}
				}
								
			} {
				logger.warn( "订单来源不是微信商城 , skip give redpacket !  orderSn : " + orderSn );
			}
			
		}else {
			logger.warn( "订单不存在 , skip give redpacket !  orderSn : " + orderSn );
		}		
}
	/** 发送开店红包 */
	private void sendOpenStoreRedPacket(String orderSn, boolean isOpenStoreOrder, Long buyUserId, Long storeUserId) {
		if (!isOpenStoreOrder) {
			logger.error("订单[{}]不是开店单，不赠送开店人[{}]兔币[{}-{}]", orderSn, buyUserId, RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getType(), RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getDesc());
			logger.error("订单[{}]不是开店单，不赠送邀请店主[{}]兔币[{}-{}]", orderSn, buyUserId, RedPacketEventTypeEnum.OLD_STORE_OWNER.getType(), RedPacketEventTypeEnum.OLD_STORE_OWNER.getDesc());
			return;
		}
		//开店店主红包
		try {
			GiveRedPacketByEventRequest request = new GiveRedPacketByEventRequest();
			request.setEventType(RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getType());
			request.setCreateTime(new Date());
			request.setInvitationUserId(storeUserId.intValue());
			request.setReceiveUserId(buyUserId.intValue());
			boolean giveRedPacketByEventType = redPacketBiz.giveRedPacketByEventType(request);
			if (!giveRedPacketByEventType) {
				logger.error("开店单[{}]赠送开店人[{}-->{}]兔币[{}-{}]失败", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getType(), RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getDesc());
			} else {
				logger.warn("开店单[{}]赠送开店人[{}-->{}]兔币[{}-{}]", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getType(), RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getDesc());
			}
		} catch (Exception e) {
			logger.error("开店单[{}]赠送开店人[{}-->{}]兔币[{}-{}]异常：{}", orderSn, storeUserId, buyUserId, RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getType(), RedPacketEventTypeEnum.NEW_STORE_OWNER_AWARD.getDesc(), e.getMessage(), e);
		}
		//邀请开店店主红包
		try {
			GiveRedPacketByEventRequest request = new GiveRedPacketByEventRequest();
			request.setEventType(RedPacketEventTypeEnum.OLD_STORE_OWNER.getType());
			request.setCreateTime(new Date());
			//			request.setInvitationUserId(storeUserId.intValue());
			request.setReceiveUserId(storeUserId.intValue());
			boolean giveRedPacketByEventType = redPacketBiz.giveRedPacketByEventType(request);
			if (!giveRedPacketByEventType) {
				logger.error("开店单[{}]赠送邀请开店店主[{}-->{}]兔币[{}-{}]失败", orderSn, buyUserId, storeUserId, RedPacketEventTypeEnum.OLD_STORE_OWNER.getType(), RedPacketEventTypeEnum.OLD_STORE_OWNER.getDesc());
			} else {
				logger.warn("开店单[{}]赠送邀请开店店主[{}-->{}]兔币[{}-{}]", orderSn, buyUserId, storeUserId, RedPacketEventTypeEnum.OLD_STORE_OWNER.getType(), RedPacketEventTypeEnum.OLD_STORE_OWNER.getDesc());
			}
		} catch (Exception e) {
			logger.error("开店单[{}]赠送邀请开店店主[{}-->{}]兔币[{}-{}]异常：{}", orderSn, buyUserId, storeUserId, RedPacketEventTypeEnum.OLD_STORE_OWNER.getType(), RedPacketEventTypeEnum.OLD_STORE_OWNER.getDesc(), e.getMessage(), e);
		}
	}

	/** 发送首单兔币 */
	private void sendFirstOrderRedPacket(String orderSn, boolean buyUserIsStoreUser, boolean isOpenStoreOrder, Long buyUserId, Long storeUserId) {
		try {
			if (buyUserIsStoreUser) {
				logger.error("订单[{}]是店主下单，不属于首单，不赠送[{}-{}]兔币", orderSn, RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getType(), RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getDesc());
				return;
			}
			if (isOpenStoreOrder) {
				logger.error("订单[{}]是开店订单，不属于首单，不赠送[{}-{}]兔币", orderSn, RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getType(), RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getDesc());
				return;
			}
			if (isFirstOrder(buyUserId)) {
				GiveRedPacketByEventRequest request = new GiveRedPacketByEventRequest();
				request.setEventType(RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getType());
				request.setCreateTime(new Date());
				request.setInvitationUserId(buyUserId.intValue());
				request.setReceiveUserId(storeUserId.intValue());
				boolean giveRedPacketByEventType = redPacketBiz.giveRedPacketByEventType(request);
				if (!giveRedPacketByEventType) {
					logger.error("首单[{}]赠送店主[{}-->{}]兔币[{}-{}]失败", orderSn, buyUserId, storeUserId, RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getType(), RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getDesc());
				} else {
					logger.warn("首单[{}]赠送店主[{}-->{}]兔币[{}-{}]", orderSn, buyUserId, storeUserId, RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getType(), RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getDesc());
				}
			}
		} catch (Exception e) {
			logger.error("判断首单[{}]赠送店主[{}-->{}]兔币[{}-{}]发生异常:{}", orderSn, buyUserId, storeUserId, RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getType(), RedPacketEventTypeEnum.INVITING_FIRST_ORDER.getDesc(), e.getMessage(), e);
		}
	}

	@Override
	public void addMQPayCallBack(String orderSn) {
		//加入消息队列
		OrderSettlementCommision orderSettlementCommision = orderSettlementCommisionMapper.selectByorderSn(orderSn);
		if (orderSettlementCommision.getStatus() == 3) {//加入消息队列
			try {
				orderQueueService.addMQPayCallBack(createMessageProperties(orderSn,JsonUtil.toJson(orderSettlementCommision)));
			} catch (Exception e) {
				logger.error("支付成功后添加结算单消息队列失败：{}", e.getMessage());
				orderSettlementCommisionMapper.updateStatus("定时任务处理", 2, 3, DateUtil.getNow(), orderSettlementCommision.getId());
			}
		}
	}

	/**
	 * **********************************************
	 * @Title: excuteUserMoney
	 * @Description: 处理积分、余额、佣金业务
	 * @param @param orderObject 父单
	 * @return void
	 * @throws @author NingChongQing
	 * @date 2017年11月11日 下午1:48:39 **********************************************
	 */
	public void excuteUserMoney(OrderObject orderObject) {
		/*查询、更新妆币事务*/
		ParamsUserXzbTransactionVo params_point = new ParamsUserXzbTransactionVo();
		params_point.setOrderObjectId(orderObject.getId());
		params_point.setTransactionStatus(-1);
		params_point.setIsDelete(0);
		params_point.setIsCustom(0);
		params_point.getBusinessTypeSet().add(12);
		params_point.getBusinessTypeSet().add(14);
		List<CUserPointTransaction> userPointTList = cUserPointTransactionService.queryAll(params_point);
		//处理新建状态妆币事务
		UserPointJournal _add_user_xzb_journal = null;
		//更新事务状态
		if (CollectionUtils.isNotEmpty(userPointTList)) {
			List<XzbTransactionUpdateVo> _sub_xzb_list = new LinkedList<>();
			for (CUserPointTransaction check_pint_transaction : userPointTList) {
				XzbTransactionUpdateVo _add_xzb_transaction_vo = new XzbTransactionUpdateVo();
				_sub_xzb_list.add(_add_xzb_transaction_vo);
				_add_xzb_transaction_vo.setId(check_pint_transaction.getId());
				_add_xzb_transaction_vo.setIsDeleteCurrentStatus(0);
				_add_xzb_transaction_vo.setTransactionStatusCurrentStatus(-1);
				_add_xzb_transaction_vo.setTransactionStatusUpdateStatus(0);//事务更新为未处理
				if (orderObject.getCashCoin() > 0 && check_pint_transaction.getBusinessTypeId() == 14) {//消费妆币事务
					_add_xzb_transaction_vo.setTransactionStatusUpdateStatus(1);//事务更新为已处理
					//记录流水
					MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(14);
					if (moneyBusinessType != null) {
						_add_user_xzb_journal = new UserPointJournal();
						_add_user_xzb_journal.setUserId(orderObject.getUserId());//发生用户ID
						_add_user_xzb_journal.setBusinessTypeId(moneyBusinessType.getTypeId());//业务类型ID
						_add_user_xzb_journal.setBusinessTypeName(moneyBusinessType.getTypeName());//业务类型名称
						_add_user_xzb_journal.setAmount(-orderObject.getCashCoin().longValue());//发生金额 允许负数
						_add_user_xzb_journal.setIsCustom(0);//是否手工处理单据
						_add_user_xzb_journal.setIsDelete(0);//是否删除 0 未删除 1已删除
						_add_user_xzb_journal.setBusinessSourceId(check_pint_transaction.getId());//业务源单ID
						_add_user_xzb_journal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());// 财务记账类型
					} else {
						logger.error("订单[{}]消费妆币[{}]未记账", orderObject.getId(), orderObject.getCashCoin());
					}
				}
			}
			cUserPointTransactionService.modify(_sub_xzb_list);
		}

		/*查询、更新余额事务*/
		ParamsCommisionVo paramsCommisionVo = new ParamsCommisionVo();
		paramsCommisionVo.setStatus(0);
		paramsCommisionVo.setResult(0);
		paramsCommisionVo.setOrderObjectId(orderObject.getId());
		paramsCommisionVo.getBusinessTypeSet().add(1);
		paramsCommisionVo.getBusinessTypeSet().add(2);
		paramsCommisionVo.getBusinessTypeSet().add(3);
		paramsCommisionVo.getBusinessTypeSet().add(5);//消费余额
		paramsCommisionVo.getBusinessTypeSet().add(17);
		List<Commision> commisionList = commissionService.queryAll(paramsCommisionVo);

		UserJournal _add_balance_journal = null;
		//更新事务状态
		if (CollectionUtils.isNotEmpty(commisionList)) {
			List<CommisionUpdateStatusVo> _update_commission_list = new LinkedList<>();
			for (Commision check_commision : commisionList) {
				CommisionUpdateStatusVo _add_commision_update_status = new CommisionUpdateStatusVo();
				_update_commission_list.add(_add_commision_update_status);
				_add_commision_update_status.setId(check_commision.getId());
				_add_commision_update_status.setResultUpdateStatus(0);
				_add_commision_update_status.setResultCurrentStatus(0);
				_add_commision_update_status.setStatusUpdateStatus(1);
				_add_commision_update_status.setStatusCurrentStatus(0);
				if (orderObject.getBalancePaid() > 0 && check_commision.getBusinessTypeId() == 5) {
					_add_commision_update_status.setResultUpdateStatus(1);//已处理
					_add_commision_update_status.setResultTime(DateUtils.getFullDate());

					//记录流水
					MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(5);
					if (moneyBusinessType != null) {
						//封装流水
						_add_balance_journal = new UserJournal();
						_add_balance_journal.setUserId(orderObject.getUserId());
						_add_balance_journal.setCommisionId(check_commision.getId());
						_add_balance_journal.setOrderSn(orderObject.getOrderSn());
						_add_balance_journal.setPromotionDetailId(orderObject.getPromotionId());
						_add_balance_journal.setMoney(orderObject.getBalancePaid());
						_add_balance_journal.setComment(moneyBusinessType.getTypeName());
						_add_balance_journal.setStatus(UserJournalStatusEnum.S7.getCode());
						_add_balance_journal.setType(CommonConstants.USER_JOURNAL_TYPE_SUB);
						_add_balance_journal.setBusinessTypeId(moneyBusinessType.getTypeId());
						_add_balance_journal.setBusinessTypeName(moneyBusinessType.getTypeName());
						_add_balance_journal.setIsDelete(0);
						_add_balance_journal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());
					} else {
						logger.error("订单[{}]消费余额[{}]未记账", orderObject.getId(), orderObject.getCashCoin());
					}
				}
			}
			commissionService.modify(_update_commission_list);
		}

		//释放冻结妆币、余额，记录流水
		if (orderObject.getCashCoin() > 0 || orderObject.getBalancePaid() > 0) {
			UserWalletVo userWallet = getUserWallet(orderObject.getUserId());
			List<CUserMoneyChange> _add_user_money_change_list = new LinkedList<>();
			if (orderObject.getCashCoin() > 0) {
				if (orderObject.getTotalFee().intValue() > 0) {//非零元付订单
					//扣减用户冻结妆币
					if (userMoneyService.updateSubFrozenAmount(userWallet.getXzb().getId(), orderObject.getUserId(), orderObject.getCashCoin())) {
						// 记录用户资产的变化
						CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
						_add_user_money_change_list.add(addCUserMoneyChange);

						addCUserMoneyChange.setUserId(orderObject.getUserId());
						addCUserMoneyChange.setOrderSn(orderObject.getId());// 源ID
						addCUserMoneyChange.setExtend1(orderObject.getOrderSn());
						addCUserMoneyChange.setChangeAmount(0);
						addCUserMoneyChange.setNormalBeforAmount(userWallet.getXzb().getAvailQuantity());
						addCUserMoneyChange.setFreeBeforAmount(userWallet.getXzb().getFrozenQuantity());
						addCUserMoneyChange.setSourceType(Byte.valueOf("2"));// 积分
						addCUserMoneyChange.setChangeFreeAmount(-orderObject.getCashCoin());
					}
				}
				if (_add_user_xzb_journal != null) {//记录消费妆币流水
					userPointJournalService.addSelective(_add_user_xzb_journal);
				} else {
					logger.error("订单[{}]消费妆币[{}]未记账", orderObject.getId(), orderObject.getCashCoin());
				}
			}
			if (orderObject.getBalancePaid() > 0) {
				if (orderObject.getTotalFee().intValue() > 0) {//非零元付订单
					//扣减用户冻结余额
					if (userMoneyService.updateSubFrozenAmount(userWallet.getBalance().getId(), orderObject.getUserId(), orderObject.getBalancePaid())) {
						// 记录用户资产的变化
						CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
						_add_user_money_change_list.add(addCUserMoneyChange);

						addCUserMoneyChange.setUserId(orderObject.getUserId());
						addCUserMoneyChange.setOrderSn(orderObject.getId());// 源ID
						addCUserMoneyChange.setExtend1(orderObject.getOrderSn());
						addCUserMoneyChange.setChangeAmount(0);
						addCUserMoneyChange.setNormalBeforAmount(userWallet.getBalance().getNormalAmount());
						addCUserMoneyChange.setFreeBeforAmount(userWallet.getBalance().getFrozenAmount());
						addCUserMoneyChange.setSourceType(Byte.valueOf("1"));//余额
						addCUserMoneyChange.setChangeFreeAmount(-orderObject.getBalancePaid());
					}
				}
				if (_add_balance_journal != null) {//记录余额消费流水
					userJournalService.insertSelective(_add_balance_journal);
				} else {
					logger.error("订单[{}]消费余额[{}]未记账", orderObject.getId(), orderObject.getBalancePaid());
				}
			}
			//记录账户变动日志
			saveUserMoneyChange(orderObject.getUserId(), _add_user_money_change_list);
		}
	}

	/**
	 * <dl>
	 * <dt>订单验证</dt>
	 * </dl>
	 * @param userId
	 * @return UserMoneyVo
	 * @author gwq
	 * @date 2018年03月14日 下午3:07:54
	 */
	@Override
	public Map<String, Object> validationOrderObj(OrderObject orderObj) throws Exception {
		return null;
	}

	/**
	 * <dl>
	 * <dt>获取用户钱包</dt>
	 * </dl>
	 * @param userId
	 * @return UserMoneyVo
	 * @author zls
	 * @date 2017年9月5日 下午3:07:54
	 */
	protected UserWalletVo getUserWallet(long userId) {
		List<UserMoney> userMoneys = userMoneyService.selectUserMoney(userId);
		UserWalletVo userMoneyVo = new UserWalletVo();
		if (CollectionUtils.isNotEmpty(userMoneys)) {
			for (UserMoney userMoney : userMoneys) {
				//余额
				if (UserMoenyTypeEnum.C1.getCode() == userMoney.getType()) {
					userMoneyVo.getBalance().setId(userMoney.getId());
					userMoneyVo.getBalance().setNormalAmount(userMoney.getNormalAmount() == null ? 0 : userMoney.getNormalAmount());
					userMoneyVo.getBalance().setFrozenAmount(userMoney.getFrozenAmount() == null ? 0 : userMoney.getFrozenAmount());
					userMoneyVo.getBalance().setLimitAmount(userMoneyVo.getBalance().getNormalAmount());
				}
				//妆币
				else if (UserMoenyTypeEnum.C2.getCode() == userMoney.getType()) {
					userMoneyVo.getXzb().setId(userMoney.getId());
					userMoneyVo.getXzb().setAvailQuantity(userMoney.getNormalAmount() == null ? 0 : userMoney.getNormalAmount());
					userMoneyVo.getXzb().setFrozenQuantity(userMoney.getFrozenAmount() == null ? 0 : userMoney.getFrozenAmount());
					userMoneyVo.getXzb().setLimitQuantity(userMoneyVo.getXzb().getAvailQuantity());
				}
			}
		}
		return userMoneyVo;
	}

	/** 下单所在店铺用户 */
	protected ResponseUser getStoreUser(ReqHeaderVo reqHeader, ResponseUser loginUser, Long talentId) throws PlatformException {
		ResponseUser _store_user = null;
		if (talentId == null) {
			talentId = 0l;
		}
		if (reqHeader.isWX()) {//wx渠道
			if (talentId > 0) {//店铺取talentId
				ResponseUser _talent_user = userService.selectUserRoleById(talentId);
				if (_talent_user == null) {
					warnLog(reqHeader, "talentId{}不存在", talentId);
					throw new PlatformException(ErrorEnum.C20111, "店铺无效");
				}
				if (_talent_user.isStoreLevel()) {
					_store_user = _talent_user;
				} else {
					warnLog(reqHeader, "talentId{}不是店主级别{}-{}", talentId, _talent_user.getRoleId(), _talent_user.getLevel());
					throw new PlatformException(ErrorEnum.C20111, "店铺【" + _talent_user.getNickName() + "】无效");
				}
			} else {//正常下单，取下单人
				warnLog(reqHeader, "talentId为空");
				throw new PlatformException(ErrorEnum.C20102, "店铺无效");
			}
		} else if (reqHeader.isAndroid() || reqHeader.isiOS()) {//android、iOS渠道
			if (loginUser.isStoreLevel()) {//正常下单取下单人
				_store_user = loginUser;
			} else {
				warnLog(reqHeader, "下单人{}不是店主{}-{}", loginUser.getUserId(), loginUser.getRoleId(), loginUser.getLevel());
				throw new PlatformException(ErrorEnum.C20111, "店铺" + loginUser.getNickName() + "无效，暂时无法购买");
			}
		} else {//其它渠道
			errorLog(reqHeader, "暂时不支持下单");
			throw new PlatformException(ErrorEnum.C20111, "暂时不支持下单");
		}
		if (_store_user == null) {
			warnLog(reqHeader, "用户[{}]所在店铺不存在[{}]", loginUser.getUserId(), talentId);
			throw new PlatformException(ErrorEnum.C20111, "店铺异常，暂时无法购买");
		}
		//设置店主身份ID
		UserInfo checkStoreUserInfo = userService.selectUserInfoFormCacheByUserId(_store_user.getUserId());
		if (checkStoreUserInfo == null) {
			warnLog(reqHeader, "用户[{}]所在的店铺[{}]身份信息不存在", loginUser.getUserId(), _store_user.getUserId());
			throw new PlatformException(ErrorEnum.C20111, "店铺异常，暂时无法购买");
		} else {
			_store_user.setPersionId(checkStoreUserInfo.getPersionId());
		}
		//校验店铺上级是否存在
		if (_store_user.isOrdinaryLevel() || _store_user.isSalesman()) {//普通店主
			if (StringUtils.isBlank(_store_user.getRecommendFrom())) {
				warnLog(reqHeader, "店主{}的身份为空", _store_user.getUserId());
				throw new PlatformException(ErrorEnum.C20111, "店铺【" + _store_user.getNickName() + "】异常，暂时无法购买");
			}
			if (StringUtils.isBlank(_store_user.getTalentTeacher())) {
				warnLog(reqHeader, "店主{}上级为空", _store_user.getUserId());
				throw new PlatformException(ErrorEnum.C20111, "店铺【" + _store_user.getNickName() + "】异常，暂时无法购买");
			}
		} else if (_store_user.isSupervisor()) {//导师、督导
			if (StringUtils.isBlank(_store_user.getRecommendFrom())) {
				warnLog(reqHeader, "导师/督导店铺{}的身份为空", _store_user.getUserId());
				throw new PlatformException(ErrorEnum.C20111, "店铺【" + _store_user.getNickName() + "】异常，暂时无法购买");
			}
		} else {//异常级别
			warnLog(reqHeader, "店铺{}的级别非法{}-{}", _store_user.getUserId(), _store_user.getRoleId(), _store_user.getLevel());
			throw new PlatformException(ErrorEnum.C20111, "店铺【" + _store_user.getNickName() + "】异常，暂时无法购买");
		}
		//店铺推荐人
		if (StringUtils.isBlank(_store_user.getRecommendFrom())) {
			warnLog(reqHeader, "店铺{}推荐身份为空 {}-{}", _store_user.getUserId(), _store_user.getRecommendFrom(), _store_user.getTalentTeacher());
			throw new PlatformException(ErrorEnum.C20111, "店铺【" + _store_user.getNickName() + "】异常，暂时无法购买");
		}
		return _store_user;
	}

	/** 是否是首单 */
	protected boolean isOpenOrderStore(RequestOrderDetail reqOrderDetail, Map<Long, InventoryVo> checkInventoryMap, ResponseUser loginUser, Set<Long> productIds) throws PlatformException {
		boolean isOpenStoreOrder = false;
		int open_store_goods_nums = 0;//开店商品种类
		int open_store_goods_quantity = 0;//开店商品数量
		List<OrderDetail> orderDetailList = reqOrderDetail.getOrderDetailList();
		for (OrderDetail orderDetail : orderDetailList) {
			InventoryVo inventoryVo = checkInventoryMap.get(orderDetail.getInventoryId());
			if (inventoryVo.isOpenGoods()) {
				open_store_goods_nums++;
				open_store_goods_quantity += orderDetail.getQuantity();
				if (!isOpenStoreOrder) {
					isOpenStoreOrder = true;
				}
			}
			productIds.add(inventoryVo.getProductId());
		}
		if (isOpenStoreOrder) {
			if (reqOrderDetail.getRedPacket() != null) {
				warnLog(reqOrderDetail.getReqHeader(), "购买开店礼包不允许使用兔币[{}]-用户[{}]", reqOrderDetail.getRedPacket().getOwnerId(), loginUser.getUserId());
				throw new PlatformException(ErrorEnum.C20133, "购买开店礼包无法使用兔币");
			}
			if (reqOrderDetail.getPromotionId() > 0) {
				warnLog(reqOrderDetail.getReqHeader(), "购买开店礼包不允许使用优惠券[{}]-用户[{}]", reqOrderDetail.getRedPacket().getOwnerId(), loginUser.getUserId());
				throw new PlatformException(ErrorEnum.C20133, "购买开店礼包无法使用优惠券");

			}
			checkOpenStoreOrder(reqOrderDetail.getReqHeader(), loginUser, productIds.size(), open_store_goods_nums, open_store_goods_quantity, reqOrderDetail.getBalanceAmount(), reqOrderDetail.getCashCoin());
		}
		return isOpenStoreOrder;
	}

	/** 校验开店订单信息 */
	protected void checkOpenStoreOrder(ReqHeaderVo reqHeader, ResponseUser loginUser, int productNums, int open_store_goods_nums, int open_store_goods_quantity, int balanceAmount, int cashCoin) throws PlatformException {
		//限定可购买渠道
		if (unableBuyChannel(reqHeader)) {
			warnLog(reqHeader, "用户[{}]在本渠道暂时无法购买开店礼包", loginUser.getUserId());
			throw new PlatformException(ErrorEnum.C20133, "本渠道暂时无法购买开店礼包");
		}
		//店主无法购买开店商品
		if (loginUser.isStoreLevel()) {
			warnLog(reqHeader, "用户[{}]已经是店主级别[{}-{}]，无法购买开店礼包", loginUser.getUserId(), loginUser.getRoleId(), loginUser.getLevel());
			throw new PlatformException(ErrorEnum.C20133, "您已经购买过开店礼包");
		}
		//商品种类2种以上
		if (productNums != 1) {
			warnLog(reqHeader, "用户[{}] 开店单一次只能购买一种商品[{}]", loginUser.getUserId(), productNums);
			throw new PlatformException(ErrorEnum.C20133, "开店礼包不能与其它商品一起购买");
		}
		//开店礼包只能购买1个
		if (open_store_goods_quantity != 1) {
			warnLog(reqHeader, "用户[{}] 开店单一次只能购买1个[{}]", loginUser.getUserId(), productNums);
			throw new PlatformException(ErrorEnum.C20133, "开店礼包只能购买一个");
		}
		//开店礼包只能购买1种
		if (open_store_goods_nums != 1) {
			warnLog(reqHeader, "用户[{}] 开店单一次只能购买一种开店商品[{}]", loginUser.getUserId(), open_store_goods_nums);
			throw new PlatformException(ErrorEnum.C20133, "开店礼包每次只能购买一种");
		}
		//钱包不可使用
		if (balanceAmount > 0 || cashCoin > 0) {
			warnLog(reqHeader, "用户[{}] 开店单不可使用妆币或余额[{}-{}]", loginUser.getUserId(), cashCoin, balanceAmount);
			throw new PlatformException(ErrorEnum.C20133, "购买开店礼包无法使用余额或妆币，请使用现金支付");
		}
		//校验是否已经有开店单
		List<OrderObject> _check_open_store_order_list = orderDao.selectOpenOrder(loginUser.getUserId());
		if (CollectionUtils.isNotEmpty(_check_open_store_order_list)) {
			warnLog(reqHeader, "用户[{}] 已经下过开店订单[{}]", loginUser.getUserId(), _check_open_store_order_list.size());
			throw new PlatformException(ErrorEnum.C21201, "您已经下过开店订单，请完成或取消之前待付款订单");
		}
	}

	/** 校验登录用户有效性 */
	protected boolean _check_login_user(ResponseUser _login_user, ResponseUser _store_user, ResponseResultModel<?> resultModel) {
		//登录用户校验
		if (!_login_user.hasRecommendFrom()) {
			logger.error("用户{}推荐人身份为空{}", _login_user.getUserId(), JSONObject.toJSONString(_login_user));
			resultModel.setError(ErrorEnum.C20111);
			resultModel.setMessage("用户信息异常，请联系客服处理");
			return true;
		}
		if (_login_user.isStoreLevel()) {
			if (!_login_user.isSalesman() && StringUtils.isBlank(_login_user.getTalentTeacher())) {
				logger.error("用户{}达人讲师身份为空{}", _login_user.getUserId(), JSONObject.toJSONString(_login_user));
				resultModel.setError(ErrorEnum.C20111);
				resultModel.setMessage("用户信息异常，请联系客服处理");
				return true;
			}
		}

		//当前登录人店主信息
		if (_store_user == null || _store_user.getUserId() == null) {
			logger.error("用户{}推荐人身份{}无效{}-{}", _login_user.getUserId(), _login_user.getRecommendFrom(), JSONObject.toJSONString(_login_user), JSONObject.toJSONString(_store_user));
			resultModel.setError(ErrorEnum.C20111);
			resultModel.setMessage("用户信息异常，请联系客服处理");
			return true;
		}
		if (_store_user.isStoreLevel()) {
			if (!_store_user.isSalesman() && !_store_user.hasTalentTeacher()) {
				logger.error("用户{}的推荐人{}的达人讲师身份为空", _login_user.getUserId(), _store_user.getUserId());
				resultModel.setError(ErrorEnum.C20111);
				resultModel.setMessage("用户信息异常，请联系客服处理");
				return true;
			}
		}
		return false;
	}

	/**
	 * <dl>
	 * <dt>更新满足开店条件的购买人身份信息</dt>
	 * </dl>
	 * @param orderObject 交易单
	 * @throws PlatformException 业务异常
	 * @author zls
	 */
	protected void updateOpenStore(OrderObject orderObject) throws PlatformException {}

	@Override
	public void updateOrderForXZOMS(String orderSn, String payId, Integer payType, String t_id) throws PlatformException {}

	@Override
	public void divide(String orderSn) throws Exception {

	}

	@Override
	public AlipayAppKeyInfo getAlipayAppKeyInfo() {
		AlipayAppKeyInfo alipayAppKeyInfo = new AlipayAppKeyInfo();
		alipayAppKeyInfo.setSellerId(AlipayConfig.sellerId);
		alipayAppKeyInfo.setAppId(AlipayConfig.appId);
		alipayAppKeyInfo.setPid(AlipayConfig.pid);
		alipayAppKeyInfo.setAppPrivateKey0(AlipayConfig.appPrivateKey0);
		alipayAppKeyInfo.setAlipayPublicKey0(AlipayConfig.alipayPublicKey0);
		alipayAppKeyInfo.setAppPrivateKey(AlipayConfig.appPrivateKey);
		alipayAppKeyInfo.setAlipayPublicKey(AlipayConfig.alipayPublicKey);
		alipayAppKeyInfo.setUrl(AlipayConfig.url);
		alipayAppKeyInfo.setCallbackUrl(AlipayConfig.callbackUrl);
		alipayAppKeyInfo.setStoreName(AlipayConfig.storeName);
		return alipayAppKeyInfo;
	}

	@Override
	public PayAppKeyInfo getPayAppKeyInfo(int payType) {
		PayAppKeyInfo payAppKeyInfo = new PayAppKeyInfo();
		if (payType == PayTypeEnum.T1.getCode()) {
			payAppKeyInfo.setAppId(PayConfig.appId0);
			payAppKeyInfo.setSecret(PayConfig.secret0);
			payAppKeyInfo.setPartnerId(PayConfig.partnerId0);
			payAppKeyInfo.setPartnerKey(PayConfig.partnerKey0);
			payAppKeyInfo.setCallbackUrl(PayConfig.callbackUrl);
			payAppKeyInfo.setStoreName(PayConfig.storeName);
			payAppKeyInfo.setCa(PayConfig.ca0);
		} else if (payType == PayTypeEnum.T3.getCode()) {
			payAppKeyInfo.setAppId(PayConfig.appId);
			payAppKeyInfo.setSecret(PayConfig.secret);
			payAppKeyInfo.setPartnerId(PayConfig.partnerId);
			payAppKeyInfo.setPartnerKey(PayConfig.partnerKey);
			payAppKeyInfo.setCallbackUrl(PayConfig.callbackUrl);
			payAppKeyInfo.setStoreName(PayConfig.storeName);
			payAppKeyInfo.setCa(PayConfig.ca);
		}
		return payAppKeyInfo;
	}

	@Override
	public List<ExpressCompany> listExpreseCompany() {
		//  Auto-generated method stub
		return ExpressCompanyMapper.selectExpreseCompany();
	}

	@Override
	public ResponseEntity<?> thirdpartyConsignment(String appKey, String data, String sign) throws Exception {
		AppSecret appSecret = AppSecretMapper.selectAppSecret(appKey);
		if (appSecret == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20150), HttpStatus.OK);
		}
		StringBuffer sg = new StringBuffer();
		// 拼接data+sign MD5加密
		String md = stringMD5(sg.append(data).append(appSecret.getSecret()).toString());
		// sign不匹配返回结果
		if (!md.equals(sign)) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20151), HttpStatus.OK);
		}
		// base64解密 json转对象
		HaigouApiAuthentication vo = JSONObject.parseObject(Base64Util.decode(data), HaigouApiAuthentication.class);
		if (StringUtils.isAnyBlank(vo.getOrderSn(), vo.getCourierNo(), vo.getExpressNo(), vo.getSendTime())) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20160), HttpStatus.OK);
		}
		// 取快递公司
		ExpressCompany exNo = expressCompanyMapper.selectCompanyByCompanyNo(vo.getExpressNo());
		// 订单号查询订单
		OrderInfo orderInfo = orderInfoMapper.selectOrderInfoEntityByOrderSn(vo.getOrderSn());
		// 数据不匹配返回结果
		if (orderInfo == null || orderInfo.getStatus() != 2) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20149), HttpStatus.OK);
		}
		// 修改订单状态为3已发货 并将快递公司编号和快递单号放入
		orderInfoMapper.updateComAndNoByOrderSn(exNo.getCompanyNo(), vo.getCourierNo(), exNo.getCompanyName(), vo.getOrderSn(), vo.getSendTime());
		// 返回成功
		orderStatusService.orderDelivery(orderInfo.getOrderSn());

		//发送出库短信
		try {
			ResponseUser buyUser = userService.selectUserRoleById(orderInfo.getUserId());
			if (buyUser != null) {
				SMSNoticeDelivery smsNoticeDelivery = new SMSNoticeDelivery(buyUser.getUserName());
				smsNoticeDelivery.setOrderSn(orderInfo.getOrderSn());
				smsNoticeDelivery.setExpressNo(vo.getCourierNo());
				smsNoticeDelivery.setExpressName(exNo.getCompanyName());
				smsNoticeDelivery.setExpressTime(vo.getSendTime());
				smsService.noticeDelivery(smsNoticeDelivery);
			}
		} catch (Exception e) {
			logger.error("出库发送短信失败:{}", e.getMessage(), e);
		}

		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	@Override
	public OrderInfo selectOrderInfoByOrderInfoSn(String orderSn) {
		//  Auto-generated method stub
		return orderInfoMapper.selectOrderInfoEntityByOrderSn(orderSn);
	}

	@Override
	public AfterSales selectAfterSalesByCustomerServiceNumber(String customerServiceNumber) {
		//  Auto-generated method stub
		return afterSalesMapper.selectAfterSalesByCustomerServiceNumber(customerServiceNumber);
	}

	public static String stringMD5(String pw) {
		try {

			// 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 输入的字符串转换成字节数组
			byte[] inputByteArray = pw.getBytes();
			// inputByteArray是输入字符串转换得到的字节数组
			messageDigest.update(inputByteArray);
			// 转换并返回结果，也是字节数组，包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 字符数组转换成字符串返回
			return byteArrayToHex(resultByteArray);
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	public static String byteArrayToHex(byte[] byteArray) {

		// 首先初始化一个字符数组，用来存放每个16进制字符
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		// new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
		char[] resultCharArray = new char[byteArray.length * 2];
		// 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		// 字符数组组合成字符串返回
		return new String(resultCharArray);
	}

	// public static String getFromBase64(String s) {
	// BASE64Encoder encoder=new BASE64Encoder();
	// String asdasdas = encoder.encode(s.getBytes());
	// return asdasdas;
	// }
	public static String getFromBase64(String s) {
		byte[] b = null;
		String result = null;
		if (s != null) {
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				b = decoder.decodeBuffer(s);
				result = new String(b, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	// 确认收货
	@Override
	public ResponseEntity<?> confirmOrder(long orderInfoId) throws Exception {
		//  Auto-generated method stub
		OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderInfoId);
		if (orderInfo.getStatus() != 3) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}
		int i = orderStatusService.confirmOrder(orderInfo.getOrderSn());
		if (i == 0) {//未成功
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C50001), HttpStatus.OK);
		} else {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		}
	}

	@Override
	public void confirmOrderVip(String orderSn, int payType, int paymentFee, String payId) throws Exception {
		OrderVip orderVip = orderVipMapper.selectOrderVipByOrderSn(orderSn);
		if (payType != 2) {
			logger.info("------>微信成功回调，进入业务代码");
		} else {
			logger.info("------>支付宝成功回调，进入业务代码");
		}
		int procedureFee = 0;
		if (payType == 2) {
			procedureFee = paymentFee * 6 / 1000; // 支付宝手续费千分之六
		}
		int updateStatus = orderVipMapper.updateOrderVipWhenSuccess(orderSn, payId, paymentFee, procedureFee);
		if (updateStatus <= 0) {
			logger.error("------>回调信息写入失败");
			throw new Exception();
		}
		// 激活会员身份
		talentService.activationUserVip(orderVip.getUserId(), orderVip.getTotalFee().longValue());
	}

	@Override
	public OrderObject selectOrderObjectByOrderObjectId(Long orderObjectId) {
		//  Auto-generated method stub
		return orderObjectMapper.selectByPrimaryKey(orderObjectId);
	}

	@Override
	public List<PayTypeConfig> selectPayTypeConfigByStatus(Integer status) {
		return orderDao.selectPayTypeConfigByStatus(status);
	}

	@Override
	public List<OrderObject> selectDiTemp() {
		return orderObjectMapper.selectDiTemp();
	}

	@Override
	public void disposeOrderSettlement() {
		//  Auto-generated method stub
		List<OrderDetail> lisrOrderDetail = orderDetailMapper.disposeOrderSettlement();
		for (OrderDetail orderDetail : lisrOrderDetail) {
			//OrderObject orderObject=orderObjectMapper.selectOrderObjectById(orderDetail.getOrderObjectId());
			OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderDetail.getOrderId());
			OrderSettlement orderSettlement = new OrderSettlement();
			orderSettlement.setOrderSn(orderInfo.getOrderSn());
			orderSettlement.setOrderDetailId(orderDetail.getId());
			orderSettlement.setOrderStatus(orderInfo.getStatus());
			orderSettlement.setPayTime(orderInfo.getPayTime());
			orderSettlement.setUserId(orderInfo.getUserId());
			Product product = productMapper.selectProductById(orderDetail.getProductId());
			orderSettlement.setProductBn(product.getProductBn());
			orderSettlement.setGoodName(orderDetail.getGoodName());
			orderSettlement.setGoodId(orderDetail.getGoodId());
			orderSettlement.setTotalPrice(orderDetail.getTotalPrice());
			orderSettlement.setTotalSettlementprice(orderDetail.getTotalSettlementprice());
			orderSettlement.setQuantity(orderDetail.getQuantity());
			orderSettlement.setSalePrice(orderDetail.getSalePrice());
			orderSettlement.setSettlementPrice(orderDetail.getSettlementPrice());
			orderSettlement.setCashCoin(orderDetail.getCashCoin());
			orderSettlement.setPromotionId(orderInfo.getPromotionId());
			orderSettlement.setPromotionDiscount(orderInfo.getPromotionDiscount());
			orderSettlement.setTotalFee(orderDetail.getTotalFee());
			Goods goods = goodsMapper.selectGoodsById(orderDetail.getGoodId());
			orderSettlement.setOperateCosting(goods.getOperateCosting());
			orderSettlement.setPayType(orderInfo.getPayType());
			orderSettlement.setLinkMan(orderInfo.getLinkMan());
			orderSettlement.setMobile(orderInfo.getMobile());
			orderSettlement.setProvince(orderInfo.getProvince());
			orderSettlement.setCity(orderInfo.getCity());
			orderSettlement.setArea(orderInfo.getArea());
			orderSettlement.setStreet(orderInfo.getStreet());
			orderSettlement.setAddress(orderInfo.getAddress());
			orderSettlement.setDeliveryWay(orderInfo.getDeliveryWay());
			orderSettlement.setExpressType(orderInfo.getExpressName());
			orderSettlement.setExpressNo(orderInfo.getExpressNo());
			orderSettlement.setStoreId(orderInfo.getStoreId());
			orderSettlement.setOrderCreateTime(orderInfo.getCreateTime());
			orderSettlement.setOrderUpdateTime(orderInfo.getUpdateTime());
			orderSettlement.setCompleteDate(orderInfo.getCompleteTime());
			orderSettlement.setRemark(orderInfo.getRemark());
			if (orderInfo.getSettlementMan() == null) {
				orderInfo.setSettlementMan("暂无");
			}
			orderSettlement.setSettlementMan(orderInfo.getSettlementMan());
			if (orderInfo.getSettlementAccount() == null) {
				orderInfo.setSettlementAccount("暂无");
			}
			orderSettlement.setSettlementAccount(orderInfo.getSettlementAccount());
			if (orderInfo.getSettlementBank() == null) {
				orderInfo.setSettlementBank("暂无");
			}

			orderSettlement.setSettlementBank(orderInfo.getSettlementBank());
			orderSettlement.setCreateTime(DateUtil.currentStringDate());
			orderSettlement.setUpdateTime(DateUtil.currentStringDate());
			orderSettlement.setStatus(1);
			orderSettlement.setGoodsType(orderDetail.getGoodsType());
			orderSettlement.setCompanyAccount("");
			orderSettlement.setManagerAccount("");
			if (orderDetail.getGoodsType() == 1) {
				Inventory inventory = inventoryMapper.selectByPrimaryKey(orderDetail.getInventoryId());
				orderSettlement.setSettlementRateDealer(inventory.getSettlementRateDealer());
				orderSettlement.setSettlementRateManager(inventory.getSettlementRateManager());
				orderSettlement.setSettlementPriceDealer((int) (Math.round((double) orderDetail.getTotalFee() * orderSettlement.getSettlementRateDealer() / 100)));
				orderSettlement.setCashCoinDealer((int) (Math.round((double) orderDetail.getCashCoin() * orderSettlement.getSettlementRateDealer() / 100)));
				orderSettlement.setSettlementPriceManager(orderDetail.getTotalFee() - orderSettlement.getSettlementPriceDealer());
				orderSettlement.setCashCoinManager(orderDetail.getCashCoin() - orderSettlement.getCashCoinDealer());
				orderSettlementMapper.insert(orderSettlement);
			} else {
				orderSettlement.setSettlementPriceDealer(0);
				orderSettlement.setSettlementPriceManager(0);
				orderSettlement.setCashCoinDealer(0);
				orderSettlement.setCashCoinManager(0);
				orderSettlement.setSettlementRateDealer(0);
				orderSettlement.setSettlementRateManager(0);
				orderSettlementMapper.insert(orderSettlement);
			}

		}
	}

	@Override
	public void OrderSettlement() {
		//  Auto-generated method stub
		List<OrderSettlement> listOrderSettlement = orderDetailMapper.selectOrderSettlement();
		for (OrderSettlement orderSettlement : listOrderSettlement) {
			OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(orderSettlement.getOrderDetailId());
			OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderDetail.getOrderId());
			Inventory inventory = inventoryMapper.selectByPrimaryKey(orderDetail.getInventoryId());
			int SettlementRateDealer = inventory.getSettlementRateDealer();
			int setSettlementRateManager = inventory.getSettlementRateManager();
			int setSettlementPriceDealer = (int) (Math.round((double) orderDetail.getTotalFee() * inventory.getSettlementRateDealer() / 100));
			int setCashCoinDealer = (int) (Math.round((double) orderDetail.getCashCoin() * inventory.getSettlementRateDealer() / 100));
			int setSettlementPriceManager = orderDetail.getTotalFee() - setSettlementPriceDealer;
			int setCashCoinManager = orderDetail.getCashCoin() - setCashCoinDealer;
			orderSettlementMapper.updateOrderSettlementPortionMessage(orderInfo.getSettlementMan(), orderInfo.getSettlementAccount(), orderInfo.getSettlementBank(), orderDetail.getGoodsType(), setSettlementPriceDealer, setSettlementPriceManager, setCashCoinDealer, setCashCoinManager, SettlementRateDealer, setSettlementRateManager, orderSettlement.getId());
		}
	}

	protected void createOrderFreightSettlement(List<OrderSettlement> orderSettlementList, Map<Long, OrderInfo> orderInfoIdMap, List<OrderDetail> inOrderDetailList) throws PlatformException {

		Collection<OrderInfo> orderInfoCollection = orderInfoIdMap.values();
		List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>(orderInfoCollection);
		for (OrderInfo orderInfo : orderInfoList) {
			//设置分账金额
			int infototalFee = orderInfo.getTotalFee() == null ? 0 : orderInfo.getTotalFee().intValue();
			int infoFreight = orderInfo.getFreight() == null ? 0 : orderInfo.getFreight().intValue();
			int infoCashcoin = orderInfo.getCashCoin() == null ? 0 : orderInfo.getCashCoin().intValue();
			int infoBalance = orderInfo.getBalancePaid() == null ? 0 : orderInfo.getBalancePaid().intValue();
			int infoPromotion = orderInfo.getPromotionDiscount() == null ? 0 : orderInfo.getPromotionDiscount().intValue();
			int infototalPrice = orderInfo.getTotalPrice() == null ? 0 : orderInfo.getTotalPrice().intValue();
			long infoDiscountFee = orderInfo.getoActivDiscountFee();//订单活动抵扣金额
			//			int divideFee=infototalFee>=infoFreight?infoFreight:infototalFee;
			//			boolean  dickou=(infototalPrice-infoBalance-infoCashcoin-infoPromotion)<=0?true:false;

			int orderinfoCashCoinFreight = 0;
			int orderinfoBalanceFreight = 0;
			int orderinfoFeeFreight = 0;//现金
			/*if(divideFee==0){
				continue;//运费被账户抵消了 不进行分账
			}*/

			if (infoFreight > 0) {//计算运费的分账信息
				int detailCashCoincount = 0;//子单妆币累计
				int detailBalancePaidcount = 0;//子单余额累计
				int detailTotalpricecount = 0;
				int detailTotalFeecount = 0;
				int detailPromotioncount = 0;
				int detailActivFee = 0;//订单明细活动抵扣金额累计总和
				for (OrderDetail detail : inOrderDetailList) {
					if (orderInfo.getId() != null && detail.getOrderId() != null && orderInfo.getId().longValue() == detail.getOrderId().longValue()) {
						detailCashCoincount += detail.getCashCoin() == null ? 0 : detail.getCashCoin().intValue();
						detailBalancePaidcount += detail.getBalancePaid() == null ? 0 : detail.getBalancePaid().intValue();
						detailTotalpricecount += detail.getTotalPrice() == null ? 0 : detail.getTotalPrice().intValue();
						detailTotalFeecount += detail.getTotalFee() == null ? 0 : detail.getTotalFee().intValue();
						detailPromotioncount += detail.getPromotionDiscount() == null ? 0 : detail.getPromotionDiscount().intValue();
						detailActivFee += detail.getoActivDiscountFee();
					}
				}
				//detail 验证
				if (detailTotalpricecount - detailCashCoincount - detailBalancePaidcount - detailPromotioncount - detailActivFee != detailTotalFeecount) {
					logger.error("拆单后明细单detail和info金额核对有误:{}-{}", JSONObject.toJSONString(orderInfo), JSONObject.toJSONString(inOrderDetailList));
					throw new PlatformException(ErrorEnum.C20000, "下单异常，请稍后再试");
				}
				if (infototalPrice - infoBalance - infoCashcoin - infoPromotion - infoDiscountFee + infoFreight != infototalFee) {
					logger.error("拆单后明细单info不对{}", JSONObject.toJSONString(orderInfo));
					throw new PlatformException(ErrorEnum.C20000, "下单异常，请稍后再试");
				}
				orderinfoCashCoinFreight = infoCashcoin - detailCashCoincount;
				orderinfoBalanceFreight = infoBalance - detailBalancePaidcount;
				orderinfoFeeFreight = infototalFee - detailTotalFeecount;
				if (orderinfoCashCoinFreight + orderinfoBalanceFreight + orderinfoFeeFreight != infoFreight) {
					logger.error("拆单后明细单detail和info核对运费有误:{}-{}", JSONObject.toJSONString(orderInfo), JSONObject.toJSONString(inOrderDetailList));
					throw new PlatformException(ErrorEnum.C20000, "下单异常，请稍后再试");
				}
			}
			OrderSettlement orderSettlement = new OrderSettlement();
			orderSettlement.setOrderSn(orderInfo.getOrderSn());
			orderSettlement.setOrderDetailId(0 - orderInfo.getId());//给个负值
			orderSettlement.setProductBn("");
			orderSettlement.setGoodId(0L);
			orderSettlement.setGoodsType(GoodsTypeEnum.T1.getCode());//默认B区商品
			orderSettlement.setOrderStatus(orderInfo.getStatus());
			orderSettlement.setUserId(orderInfo.getUserId());
			orderSettlement.setTotalPrice(infoFreight);
			orderSettlement.setTotalSettlementprice(infoFreight);
			orderSettlement.setQuantity(0);
			orderSettlement.setOperateCosting(0);
			orderSettlement.setSettlementPrice(infoFreight);
			orderSettlement.setSalePrice(infoFreight);
			orderSettlement.setGoodName(CommonConstants.FREIGTH_SETTMENT);
			orderSettlement.setTotalFee(orderinfoFeeFreight);//运费实付清分总额
			orderSettlement.setCashCoin(orderinfoCashCoinFreight);
			orderSettlement.setBalancePaid(orderinfoBalanceFreight);

			//设置分账比例
			if (orderInfo.getStoreId().intValue() == StoreTypeEnum.T13.getCode()) {//13 非自营
				orderSettlement.setStoreId(orderInfo.getStoreId());
				orderSettlement.setSelfSupport(GoodsSelfTypeEnum.T1.getCode());
				orderSettlement.setSettlementRateDealer(freightSettlementLimitEnum.T1.getRateDealer());
				orderSettlement.setSettlementRateManager(freightSettlementLimitEnum.T1.getRateManager());
				orderSettlement.setSettlementPriceDealer((int) (Math.round((double) orderSettlement.getTotalFee() * orderSettlement.getSettlementRateDealer() / 100)));
				orderSettlement.setSettlementPriceManager(orderSettlement.getTotalFee() - orderSettlement.getSettlementPriceDealer());
			} else {//14 自营
				orderSettlement.setStoreId(orderInfo.getStoreId());
				orderSettlement.setSelfSupport(GoodsSelfTypeEnum.T0.getCode());
				orderSettlement.setSettlementRateDealer(freightSettlementLimitEnum.T0.getRateDealer());
				orderSettlement.setSettlementRateManager(freightSettlementLimitEnum.T0.getRateManager());
				orderSettlement.setSettlementPriceDealer((int) (Math.round((double) orderSettlement.getTotalFee() * orderSettlement.getSettlementRateDealer() / 100)));
				orderSettlement.setSettlementPriceManager(orderSettlement.getTotalFee() - orderSettlement.getSettlementPriceDealer());
			}
			orderSettlement.setPayType(orderInfo.getPayType());
			orderSettlement.setLinkMan(orderInfo.getLinkMan());
			orderSettlement.setMobile(orderInfo.getMobile());
			orderSettlement.setProvince(orderInfo.getProvince());
			orderSettlement.setCity(orderInfo.getCity());
			orderSettlement.setArea(orderInfo.getArea());
			orderSettlement.setStreet(orderInfo.getStreet());
			orderSettlement.setAddress(orderInfo.getAddress());
			orderSettlement.setDeliveryWay(orderInfo.getDeliveryWay());
			orderSettlement.setOrderCreateTime(orderInfo.getCreateTime());
			orderSettlement.setOrderUpdateTime(orderInfo.getUpdateTime());
			orderSettlement.setRemark(orderInfo.getRemark());
			orderSettlement.setSettlementMan(orderInfo.getSettlementMan());
			orderSettlement.setSettlementAccount(orderInfo.getSettlementAccount());
			orderSettlement.setSettlementBank(orderInfo.getSettlementBank());
			orderSettlementList.add(orderSettlement);
		}

	}

	/** 扣减库存 */
	protected void _subInventory(ResponseUser _login_user, OrderDetail orderDetail) {
		BaseRestrictions ret = baseRestrictionsService.getBaseRestrictionsForCache("skip_inventory_ids");
		boolean is_sub = true;//是否扣减库存
		if (ret != null && !StringUtils.isEmpty(ret.getName())) {
			is_sub = !ArrayUtils.contains(StringUtils.split(ret.getCreateTime(), ","), orderDetail.getInventoryId().toString());
		}

		if (is_sub) {
			//扣减库存
			int inResult = orderDao.subInventoryNumById(orderDetail.getInventoryId(), orderDetail.getQuantity());
			if (inResult != 1) {
				throw new PlatformException(ErrorEnum.C20409, "【" + orderDetail.getGoodName() + "】库存不足");
			}
			if (orderDetail.getLimitTimeSaleId() != 0) {//分时抢购限购数
				int subSkuCountNums = limitTimeSaleDetailMapper.updateSubSkuCount(_login_user.getUserId(), orderDetail.getLimitTimeSaleId(), orderDetail.getLimitTimeSaleDetailId(), orderDetail.getProductId(), orderDetail.getInventoryId(), orderDetail.getQuantity());
				if (subSkuCountNums != 1) {
					throw new PlatformException(ErrorEnum.C20409, "【" + orderDetail.getGoodName() + "】库存不足");
				}
			}
		}
	}

	@Override
	public String compareDivide(List<OrderSettlementVo> listSettle, Map<String, Double> YeePayDivide) {
		return null;
	}

	@Override
	public boolean addOrder_settlement_commision(String orderSn) throws Exception {
		boolean result = false;
		OrderObject orderObject = orderObjectMapper.selectByOrderSn(orderSn);
		OrderSettlementCommision orderSettlementCommision = orderSettlementCommisionMapper.selectByorderSn(orderSn);
		if (orderSettlementCommision != null && orderSettlementCommision.getStatus() == 3) {//还没有被执行 正在执行中
			ResponseUser loginUser = userService.selectUserRoleById(orderObject.getUserId());
			Map<Long, InventoryVo> inventoryMap = new HashMap<Long, InventoryVo>();
			createInventoryMap(inventoryMap, orderDetailMapper.selectOrderDetilByOrderObjectId(orderObject.getId()));
			Map<Long, OrderInfo> orderInfoIdMap = new HashMap<Long, OrderInfo>();
			List<OrderInfo> OrderInList = orderInfoMapper.selectOrderInfoByOrderObjectSn(orderSn);
			for (OrderInfo orderInfo : OrderInList) {
				orderInfoIdMap.put(orderInfo.getId(), orderInfo);
			}
			List<OrderDetail> listDetail = orderDetailMapper.selectOrderDetilByOrderObjectId(orderObject.getId());
			if (listDetail == null || listDetail.size() == 0)
				return false;
			//添加结算 分佣信息
			//result = addCommisionAndSettment(loginUser, orderObject, inventoryMap, orderInfoIdMap, baseRestrictionsMap);
			result = addCommisionSettment(loginUser, orderObject, inventoryMap, orderInfoIdMap);
			// 处理积分、余额、佣金业务
			this.excuteUserMoney(orderObject);
			//更新开店单信息（主要更新购买人身份信息）
			updateOpenStore(orderObject);
			//如果是开店单佣金直接到账
			OpenStoreCommisionToAccount(orderObject, orderInfoIdMap);
			orderSettlementCommisionMapper.updateStatus("已支付", 4, orderSettlementCommision.getStatus(), DateUtil.getNow(), orderSettlementCommision.getId());
		}
		return result;
	}

	@Override
	public boolean addOrder_settlement_commision(OrderSettlementCommision orderSettlementCommision) throws Exception {
		boolean result = false;
		try {
			OrderObject orderObject = orderObjectMapper.selectByOrderSn(orderSettlementCommision.getOrderSn());
			if (orderSettlementCommision != null && orderSettlementCommision.getStatus() == 3) {//还没有被执行 正在执行中
				ResponseUser loginUser = userService.selectUserRoleById(orderObject.getUserId());
				Map<Long, InventoryVo> inventoryMap = new HashMap<Long, InventoryVo>();
				createInventoryMap(inventoryMap, orderDetailMapper.selectOrderDetilByOrderObjectId(orderObject.getId()));
				Map<Long, OrderInfo> orderInfoIdMap = new HashMap<Long, OrderInfo>();
				List<OrderInfo> OrderInList = orderInfoMapper.selectOrderInfoByOrderObjectSn(orderSettlementCommision.getOrderSn());
				for (OrderInfo orderInfo : OrderInList) {
					orderInfoIdMap.put(orderInfo.getId(), orderInfo);
				}
				List<OrderDetail> listDetail = orderDetailMapper.selectOrderDetilByOrderObjectId(orderObject.getId());
				if (listDetail == null || listDetail.size() == 0)
					return false;
//				Map<String, BaseRestrictions> baseRestrictionsMap = selectAllBaseRestrictions();
				//添加结算 分佣信息
				//result = addCommisionAndSettment(loginUser, orderObject, inventoryMap, orderInfoIdMap, baseRestrictionsMap);
				result = addCommisionSettment(loginUser, orderObject, inventoryMap, orderInfoIdMap);
				// 处理积分、余额、佣金业务
				this.excuteUserMoney(orderObject);
				//更新开店单信息（主要更新购买人身份信息）
				updateOpenStore(orderObject);
				//如果是开店单佣金直接到账
				OpenStoreCommisionToAccount(orderObject, orderInfoIdMap);
				orderSettlementCommisionMapper.updateStatus(orderSettlementCommision.getErrorMsg() + " 完成", 4, orderSettlementCommision.getStatus(), DateUtil.getNow(), orderSettlementCommision.getId());
			}
		} catch (Exception e) {
			orderSettlementCommisionMapper.updateStatus1(e.getMessage() != null && e.getMessage().length() > 100 ? e.getMessage().substring(0, 100) : e.getMessage(), 5, DateUtil.getNow(), orderSettlementCommision.getId());
			logger.error("消息队列生成计算单失败：{}", e);
			throw new Exception(e.getMessage());
		}
		return result;
	}

	@Override
	public Map<String, Object> canOrder(RequestOrderDetail reqOrderDetail) {
		ReqHeaderVo ReqHeader = reqOrderDetail.getReqHeader();
		Long userId = reqOrderDetail.getUserId();
		boolean OverSeasGoods = false;
		for (OrderDetail d : reqOrderDetail.getOrderDetailList()) {
			GoodsExtends goodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(d.getGoodId());
			if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1) {// 是海外购
				OverSeasGoods = true;
				break;
			}
		}
		Map<String, Object> ret = new HashMap<String, Object>();
		try {
			int canOrder = 0;
			String _str_count = redisUtil.get(RedisKeys.ORDER_ADD_COUNT);
			if (!StringUtils.isBlank(_str_count)) {
				int currentOrderCount = Integer.parseInt(_str_count);
				BaseRestrictions res = baseRestrictionsService.getBaseRestrictionsForCache("O_ADD_MAX_COUNT");
				if (res != null && res.getExperience() > 0) {
					if (currentOrderCount < res.getExperience()) {//
						canOrder = 1;
					} else {
						canOrder = 0;
					}
				}
			} else {
				canOrder = 1;
			}
			ret.put("canOrder", canOrder);
			if (canOrder == 1 && OverSeasGoods) {// 可以继续下单 继续判断是否能购买海外购产品
				String PhoneType = ReqHeader.getPhoneType();
				String appSystemVersion = ReqHeader.getAppSystemVersion();
				String OverSeagoodsV = baseRestrictionsService.getBaseRestrictionsForCache("OverSeaGoodsAppVersion").getName();// 海外购最低版本 必须配置
				if (StringUtils.equalsAnyIgnoreCase(PhoneType, CommonConstants.PHONE_CLIENT_ANDROID, CommonConstants.PHONE_CLIENT_IOS) && StringUtil.compareVersion(appSystemVersion, OverSeagoodsV) < 0) {
					ret.put("canOverSea", 0);
				}

			}
		} catch (Exception e) {
			ret.put("canOrder", 0);
			logger.error("查询REDIS失败, {}, {}", e.getMessage(), e);
		}
		if (ret != null) {
			Object olog = ret.get("canOrder");
			int _canOrder = Integer.parseInt(String.valueOf(olog));
			if (_canOrder == 0) {
				logger.error("订单下单被丢弃|{}|{}", userId, DateUtil.getNow());
			}

		}
		return ret;
	}

	/** 不购买渠道 */
	protected boolean unableBuyChannel(ReqHeaderVo reqHeader) {
		return !reqHeader.isWX();
	}

	/**
	 * 校验分享人与分享商品
	 */
	protected boolean _check_share_goods_and_talent(long checkTalentIdReq, long talentId, long goodsId, long talentShareGoodId, ResponseResultModel<?> resultModel) {
		if (checkTalentIdReq > 0 || talentId > 0) {
			if (talentId != checkTalentIdReq) {
				resultModel.setError(ErrorEnum.C20403);
				resultModel.setMessage("分享商品不是同一个人");
				logger.warn("分享商品不是同一个人{}-{}", checkTalentIdReq, talentId);
				return true;
			}
			//			ShareGoods _check_share_goods = shareGoodsMapper.selectShareGoodsById(talentShareGoodId);
			//			if (_check_share_goods == null || talentId != _check_share_goods.getUserId() || goodsId != _check_share_goods.getGoodId()) {
			//				resultModel.setError(ErrorEnum.C20403);
			//				return true;
			//			}
		}
		return false;
	}

	/** 校验提交订单请求是否有效 */
	protected boolean _check_avail_req_get_order_obj(ResponseUser _login_user, RequestOrderDetail reqOrderDetail, ResponseResultModel<RespAddOrderInfo> resultModel) {
		ReqHeaderVo reqHeader = reqOrderDetail.getReqHeader();
		if (StringUtils.isBlank(reqOrderDetail.getReqHeader().getPhoneType())) {
			resultModel.setError(ErrorEnum.C20102);
			resultModel.setMessage("手机号为空");
			warnLog(reqHeader, "提交订单 用户[{}]手机号为空", reqOrderDetail.getUserId());
			return true;
		}
		if (reqOrderDetail.getMemberDeliveryAddressId() == null) {
			resultModel.setError(ErrorEnum.C20102);
			resultModel.setMessage("请设置收货地址");
			warnLog(reqHeader, "提交订单 用户[{}]收货地址为空", reqOrderDetail.getUserId());
			return true;
		}

		if (reqOrderDetail.getIsBill() == 1) {//有发票
			if (reqOrderDetail.getBillType() == null) {
				resultModel.setError(ErrorEnum.C20102);
				resultModel.setMessage("请选择发票类型");
				warnLog(reqHeader, "提交订单 用户[{}]发票类型为空", reqOrderDetail.getUserId());
				return true;
			} else {
				switch (reqOrderDetail.getBillType()) {
					case 2://公司
						if (StringUtils.isBlank(reqOrderDetail.getBillTaxpayerNo())) {
							resultModel.setError(ErrorEnum.C20102);
							resultModel.setMessage("请填写纳税人识别号");
							warnLog(reqHeader, "提交订单 用户[{}]纳税人识别号为空", reqOrderDetail.getUserId());
							return true;
						}
					case 1://个人
						if (StringUtils.isBlank(reqOrderDetail.getBillHeader())) {
							resultModel.setError(ErrorEnum.C20102);
							resultModel.setMessage("请填写发票抬头");
							warnLog(reqHeader, "提交订单 用户[{}]发票抬头为空", reqOrderDetail.getUserId());
							return true;
						}
						break;

					default:
						resultModel.setError(ErrorEnum.C20102);
						resultModel.setMessage("发票信息不全");
						warnLog(reqHeader, "提交订单 用户[{}]填写发票信息不全", reqOrderDetail.getUserId());
						return true;
				}
			}
		}
		if (reqOrderDetail.getRedPacket() != null) {
			if (reqOrderDetail.getRedPacket().getRedPacketId() <= 0) {
				resultModel.setError(ErrorEnum.C20102);
				resultModel.setMessage("兔币为空");
				warnLog(reqHeader, "提交订单 用户[{}]兔币ID为空[{}]", reqOrderDetail.getUserId(), reqOrderDetail.getRedPacket().getRedPacketId());
				return true;
			}
			if (reqOrderDetail.getRedPacket().getOwnerId() <= 0) {
				resultModel.setError(ErrorEnum.C20102);
				resultModel.setMessage("兔币为空");
				warnLog(reqHeader, "提交订单 用户[{}]兔币拥有记录ID为空[{}]", reqOrderDetail.getUserId(), reqOrderDetail.getRedPacket().getOwnerId());
				return true;
			}
		}
		if (reqOrderDetail.getPromotionId() < 0) {
			resultModel.setError(ErrorEnum.C20102);
			resultModel.setMessage("优惠券为空");
			warnLog(reqHeader, "提交订单 用户[{}]优惠券ID[{}]非法", reqOrderDetail.getUserId(), reqOrderDetail.getPromotionId());
			return true;
		}
		UserWalletVo userMoney = null;
		if (_login_user.isStoreLevel()) {
			userMoney = getUserWallet(reqOrderDetail.getUserId());
		} else {//非店主不允许使用妆币、余额
			userMoney = new UserWalletVo();
			if (reqOrderDetail.getBalanceAmount() > 0) {
				resultModel.setError(ErrorEnum.C29901);
				resultModel.setMessage("暂时无法使余额");
				warnLog(reqHeader, "提交订单 用户[{}]暂时无法使用余额 [{}-{}]", reqOrderDetail.getUserId(), userMoney.getBalance().getNormalAmount(), reqOrderDetail.getBalanceAmount());
				return true;
			}
			if (reqOrderDetail.getCashCoin() > 0) {
				resultModel.setError(ErrorEnum.C29901);
				resultModel.setMessage("暂时无法使妆币");
				warnLog(reqHeader, "提交订单 用户[{}]暂时无法使用妆币 [{}-{}]", reqOrderDetail.getUserId(), userMoney.getXzb().getAvailQuantity(), reqOrderDetail.getCashCoin());
				return true;
			}

		}
		if (reqOrderDetail.getBalanceAmount() > 0) {
			//余额是否充足
			if (userMoney.getBalance().getNormalAmount() < reqOrderDetail.getBalanceAmount()) {
				resultModel.setError(ErrorEnum.C29901);
				resultModel.setMessage("余额不足");
				warnLog(reqHeader, "提交订单 用户[{}]余额不足[{}-{}]", reqOrderDetail.getUserId(), userMoney.getBalance().getNormalAmount(), reqOrderDetail.getBalanceAmount());
				return true;
			}
			if (StringUtils.isBlank(reqOrderDetail.getPayPwd())) {
				resultModel.setError(ErrorEnum.C20102);
				resultModel.setMessage("支付密码为空");
				warnLog(reqHeader, "提交订单 用户[{}]支付密码为空", reqOrderDetail.getUserId());
				return true;
			}
			//校验支付密码
			UserPayInfo checkPayPwd = userPayInfoService.queryByUserId(reqOrderDetail.getUserId());
			if (checkPayPwd != null) {
				userMoney.setHasPayPwd(true);
				switch (checkPayPwd.getStatus()) {
					case 1:
						break;
					case 0:
					case 2:
						resultModel.setError(ErrorEnum.C25007);
						resultModel.setMessage("密码不可用，请重置密码");
						return true;
					default:
						resultModel.setError(ErrorEnum.C25007);
						resultModel.setMessage("密码不可用，请联系客服处理");
						return true;
				}
				if (!StringUtils.equals(reqOrderDetail.getPayPwd(), checkPayPwd.getPwd())) {
					//					resultModel.setError(ErrorEnum.C25007);
					resultModel.setMessage("密码错误");
					return true;
				} else {
					resultModel.getData().setPwdAvail(true);
				}
			} else {
				//				resultModel.setError(ErrorEnum.C25007);
				resultModel.setMessage("请设置支付密码");
				return true;
			}
		} else {
			userMoney.setHasPayPwd(userPayInfoService.existsPwd(reqOrderDetail.getUserId()));
			resultModel.getData().setPwdAvail(true);
		}
		//校妆币
		if (reqOrderDetail.getCashCoin() > 0) {
			if (userMoney.getXzb().getAvailQuantity() < reqOrderDetail.getCashCoin()) {
				resultModel.setError(ErrorEnum.C29901);
				resultModel.setMessage("妆币不足");
				warnLog(reqHeader, "提交订单 用户[{}]妆币不足[{}-{}]", reqOrderDetail.getUserId(), userMoney.getXzb().getAvailQuantity(), reqOrderDetail.getCashCoin());
				return true;
			}
		}
		resultModel.getData().setUserMoney(userMoney);
		return false;
	}

	/** 设置订单token */
	protected void _set_order_token(String token) {
		redisUtil.setex(RedisKeys.ORDER_ADD_TOKEN + token, SECONDS_ORDER_TOKEN, StringUtils.EMPTY);
		if (logger.isDebugEnabled()) {
			logger.debug("设置防重复token：{}-{}", RedisKeys.ORDER_ADD_TOKEN, token);
		}
	}

	/** 移除订单token */
	protected void _remove_order_token(String token) {
		redisUtil.del(RedisKeys.ORDER_ADD_TOKEN + token);
		if (logger.isDebugEnabled()) {
			logger.debug("移除防重复token：{}-{}", RedisKeys.ORDER_ADD_TOKEN, token);
		}
	}

	/** 校验重复提交 */
	protected boolean _check_double_submit(String token) {
		if (redisUtil.exists(RedisKeys.ORDER_ADD_TOKEN + token)) {
			_remove_order_token(token);
			return false;
		} else {
			//_set_order_token(token);
			if (logger.isDebugEnabled()) {
				logger.debug("订单结算时防重复提交token不存在：{}-{}", RedisKeys.ORDER_ADD_TOKEN, token);
			}
		}
		return true;
	}

	/**
	 * 校验分佣关系
	 */
	protected boolean _check_commission_relationship(Long talentId, int orderDetailNums, ResponseUser _login_user, OrderRecommendAndTeacherVo orderRecommendAndTeacherVo, ResponseBaseModel resultModel) {
		//获取达人
		ResponseUser talentUser = null;
		String recommendFrom;
		String talentTeacher;
		if (talentId > 0) {
			if (orderDetailNums > 1) {
				resultModel.setError(ErrorEnum.C20780);
				logger.warn("分享商品只能购买一种,分享人：{}-购买种类：{}", talentId, orderDetailNums);
				return true;
			}
			talentUser = userService.selectUserRoleById(talentId);
			if (talentUser == null) {
				resultModel.setError(ErrorEnum.C20111);
				resultModel.setMessage("商品分享人无效");
				logger.warn("商品分享人{}无效：{}", talentId, JSONObject.toJSONString(talentUser));
				return true;
			}

			recommendFrom = talentUser.getRecommendFrom();

			if (talentUser.isSalesman() || talentUser.isNotStoreLevel()) {//分享人是讲师或不是店主
				talentTeacher = "";
			} else {//分享人不是讲师
				//校验分享人的讲师
				ResponseUser _talent_teach_user = userService.selectUserRoleByPersonId(talentUser.getTalentTeacher());
				if (_talent_teach_user == null || !_talent_teach_user.isSalesman()) {
					resultModel.setError(ErrorEnum.C20111);
					resultModel.setMessage("商品分享人无效");
					logger.warn("商品分享人{}的讲师无效：{}", talentId, JSONObject.toJSONString(_talent_teach_user));
					return true;
				}
				//普通店主分享，赋值讲师身份ID
				talentTeacher = _talent_teach_user.getRecommendFrom();
				if (StringUtils.isEmpty(talentTeacher)) {
					resultModel.setError(ErrorEnum.C20111);
					resultModel.setMessage("商品分享人无效");
					logger.error("分享人{}的讲师为空", talentId);
					return true;
				}
			}
		} else {//无分享人，推荐人取当前登录人推荐人身份id，讲师取当前登录人的推荐人的讲师
			recommendFrom = _login_user.getRecommendFrom();
			//校验推荐人是否是店主级别
			ResponseUser _store_user = userService.selectUserRoleByPersonId(recommendFrom);
			if (_store_user.isSalesman()) {
				talentTeacher = "";
			} else if (_store_user.isStoreLevel()) {//推荐人是店主
				ResponseUser _teach_user = userService.selectUserRoleByPersonId(_store_user.getTalentTeacher());
				if (_teach_user == null || !_teach_user.isSalesman()) {
					resultModel.setError(ErrorEnum.C20111);
					resultModel.setMessage("您的身份信息异常，请联系客服处理");
					logger.error("小白{}身份信息异常{}-{}-{}", _login_user.getUserId(), JSONObject.toJSONString(_login_user), JSONObject.toJSONString(_store_user), JSONObject.toJSONString(_teach_user));
					return true;
				} else {
					talentTeacher = _teach_user.getRecommendFrom();
				}
			} else {
				talentTeacher = "";
			}
		}

		if (StringUtils.isEmpty(recommendFrom)) {
			resultModel.setError(ErrorEnum.C20111);
			return true;
		}
		if (orderRecommendAndTeacherVo != null) {
			orderRecommendAndTeacherVo.setRecommendFrom(recommendFrom);
			orderRecommendAndTeacherVo.setTalentTeacher(talentTeacher);
		}
		return false;
	}

	protected boolean _check_commission_relationship(long talentId, ResponseUser loginUser, ResponseUser storeUser, ResponseUser talentUser, OrderRecommendAndTeacherVo orderRecommendAndTeacherVo, ResponseBaseModel resultModel) {
		if (orderRecommendAndTeacherVo == null) {
			resultModel.setError(ErrorEnum.C20111);
			resultModel.setMessage("商品分享人无效");
			logger.warn("下单计算分佣关系为空");
			return true;
		}
		//获取达人
		String recommendFrom;
		String talentTeacher;
		if (talentId > 0) {
			if (talentUser == null) {
				resultModel.setError(ErrorEnum.C20111);
				resultModel.setMessage("商品分享人无效");
				logger.warn("商品分享人{}不存在", talentId);
				return true;
			}
			recommendFrom = talentUser.getRecommendFrom();

			if (talentUser.isSalesman() || talentUser.isNotStoreLevel()) {//分享人是讲师或不是店主
				talentTeacher = "";
			} else {//分享人不是讲师
				//校验分享人的讲师
				ResponseUser _talent_teach_user = userService.selectUserRoleByPersonId(talentUser.getTalentTeacher());
				if (_talent_teach_user == null || !_talent_teach_user.isSalesman()) {
					resultModel.setError(ErrorEnum.C20111);
					resultModel.setMessage("商品分享人无效");
					if (_talent_teach_user == null) {
						logger.warn("商品分享人{}的讲师[{}]无效", talentId, talentUser.getTalentTeacher());
					} else {
						logger.warn("商品分享人{}的讲师[{}]不是讲师级别：{}-{}", talentId, talentUser.getTalentTeacher(), _talent_teach_user.getRoleId(), JSONObject.toJSONString(_talent_teach_user));
					}
					return true;
				}
				//普通店主分享，赋值讲师身份ID
				talentTeacher = _talent_teach_user.getRecommendFrom();
				if (StringUtils.isEmpty(talentTeacher)) {
					resultModel.setError(ErrorEnum.C20111);
					resultModel.setMessage("商品分享人无效");
					logger.error("分享人{}的讲师为空", talentId);
					return true;
				}
			}
		} else {//无分享人，推荐人取当前登录人推荐人身份id，讲师取当前登录人的推荐人的讲师
			recommendFrom = loginUser.getRecommendFrom();
			//校验推荐人是否是店主级别
			if (storeUser.isSalesman()) {
				talentTeacher = "";
			} else if (storeUser.isStoreLevel()) {//推荐人是店主
				ResponseUser _teach_user = userService.selectUserRoleByPersonId(storeUser.getTalentTeacher());
				if (_teach_user == null || !_teach_user.isSalesman()) {
					resultModel.setError(ErrorEnum.C20111);
					resultModel.setMessage("您的身份信息异常，请联系客服处理");
					if (_teach_user == null) {
						logger.error("小白{}的店主{}所属讲师[{}]为空 {}-{}", loginUser.getUserId(), storeUser.getUserId(), storeUser.getTalentTeacher(), JSONObject.toJSONString(loginUser), JSONObject.toJSONString(storeUser));
					} else {
						logger.error("小白{}的店主{}所属讲师[{}]不是讲师级别{} {}-{}", loginUser.getUserId(), storeUser.getUserId(), storeUser.getTalentTeacher(), _teach_user.getRoleId(), JSONObject.toJSONString(loginUser), JSONObject.toJSONString(storeUser));
					}
					return true;
				} else {
					talentTeacher = _teach_user.getRecommendFrom();
				}
			} else {
				talentTeacher = "";
			}
		}

		if (StringUtils.isEmpty(recommendFrom)) {
			resultModel.setError(ErrorEnum.C20111);
			logger.error("用户[{}]推荐人为空", loginUser.getUserId());
			return true;
		}
		orderRecommendAndTeacherVo.setRecommendFrom(recommendFrom);
		orderRecommendAndTeacherVo.setTalentTeacher(talentTeacher);
		return false;
	}

	//	/** b区商品，只支持易宝支付，其它使用除易宝以外所有支付方式 */
	//	private List<PayTypeConfig> getPayType(String phoneType, boolean isTearcher) {
	//		return orderObjectService.queryOrderPayType(phoneType, isTearcher);
	//	}

	protected List<PayTypeConfig> getPayType(boolean isOpenStoreOrder, ReqHeaderVo reqHeader, ResponseUser payUser) {
		return orderObjectService.queryOrderPayType(isOpenStoreOrder, reqHeader, payUser);
	}

	protected List<PayTypeConfig> getPayType(ReqHeaderVo reqHeader, ResponseUser payUser) {
		return orderObjectService.queryOrderPayType(reqHeader, payUser);
	}

	/** 封装提交订单异常商品 */
	protected ErrorMsgGoods _pack_error_msg_goods(OrderDetail orderDetail, String errorMsg) {
		ErrorMsgGoods _add_err_goods = new ErrorMsgGoods();
		_add_err_goods.setGoodId(orderDetail.getGoodId());
		_add_err_goods.setGoodName(orderDetail.getGoodName());
		_add_err_goods.setSpecName(orderDetail.getSpecName());
		_add_err_goods.setGoodNavigateImage(orderDetail.getNavigateImg1());
		_add_err_goods.setInventoryId(orderDetail.getInventoryId());
		_add_err_goods.setSalePrice(orderDetail.getSalePrice());
		_add_err_goods.setProductPrice(orderDetail.getProductPrice());
		_add_err_goods.setMsg(errorMsg);
		if (CollectionUtils.isNotEmpty(orderDetail.getProductTags())) {
			_add_err_goods.getProductTags().addAll(orderDetail.getProductTags());
		}
		return _add_err_goods;
	}

	/** 封装订单赠品信息 */
	protected RespOrderGiftsProductVo _package_order_gift(OActivAvlGiftProductVo giftProduct) {
		RespOrderGiftsProductVo respOrderGiftsProductVo = new RespOrderGiftsProductVo();

		respOrderGiftsProductVo.setSalePrice(giftProduct.getSalePrice());
		respOrderGiftsProductVo.setQuantity(giftProduct.getQuantity());
		//					respOrderGiftsProductVo.setBrandName(giftProduct.getBrandName());
		respOrderGiftsProductVo.setGoodsName(giftProduct.getGoodsName());
		//					respOrderGiftsProductVo.setMsg(msg);
		respOrderGiftsProductVo.setSpecName(giftProduct.getSpecName());
		respOrderGiftsProductVo.setThumbnail(giftProduct.getThumbnail());
		return respOrderGiftsProductVo;
	}

	/** 封装订单参与活动的商品信息 */
	protected void _package_activ_order_detail(List<OrderDetail> _avl_goods_list, OrderActivInfoVo orderActivInfoVo, String nowTime) {
		if (CollectionUtils.isEmpty(_avl_goods_list)) {
			return;
		}
		Set<OActivProductParam> activProductParams = new HashSet<>();
		for (OrderDetail orderDetail : _avl_goods_list) {
			OActivProductParam addOActivProductParam = new OActivProductParam();
			activProductParams.add(addOActivProductParam);

			addOActivProductParam.setProductId(orderDetail.getProductId());
			addOActivProductParam.setSalePrice(orderDetail.getSalePrice());
			addOActivProductParam.setQuantity(orderDetail.getQuantity());
		}
		OActivAvlInfoVo queryProductActiv = oActivService.queryProductActiv(activProductParams, nowTime);
		long discountFee = 0;//优惠总金额
		boolean freeShipping = false;//免邮费

		for (OActivAvlVo activAvlVo : queryProductActiv.getAvlActivs()) {
			discountFee += activAvlVo.getDiscontFee();//优惠金额累加
			if (!freeShipping && activAvlVo.isFreeShipping()) {//是否包邮
				freeShipping = true;
			}
			OActivAvlGiftsVo gifts = activAvlVo.getGifts();
			if (CollectionUtils.isNotEmpty(gifts.getProducts())) {
				long storeId = gifts.getProducts().get(0).getStoreId();
				if (CollectionUtils.isEmpty(orderActivInfoVo.getGiftProducts().get(storeId))) {
					orderActivInfoVo.getGiftProducts().put(storeId, new LinkedList<OActivAvlGiftProductVo>());
				}
				orderActivInfoVo.getGiftProducts().get(storeId).addAll(gifts.getProducts());
			}
			for (OActivAvlProductVo activAvlProductVo : activAvlVo.getAvlActivProducts()) {
				orderActivInfoVo.getActivProducts().put(activAvlProductVo.getProductId(), activAvlProductVo);
			}
		}
		orderActivInfoVo.setDiscountFee(discountFee);
		orderActivInfoVo.setFreeShipping(freeShipping);
	}

	/** 赠品封装成订单明细实体 */
	protected List<OrderDetail> _package_gift_order_detail(long storeId, int submitType, OrderActivInfoVo orderActivInfoVo) {
		List<OrderDetail> storeOrderDetails = new LinkedList<>();
		List<OActivAvlGiftProductVo> gifts = orderActivInfoVo.getGiftProducts().get(storeId);
		if (CollectionUtils.isNotEmpty(gifts)) {
			for (OActivAvlGiftProductVo oActivAvlGiftProductVo : gifts) {
				if (oActivAvlGiftProductVo.getInventoryNum() < oActivAvlGiftProductVo.getQuantity() && submitType == 1) {
					continue;
				}
				OrderDetail addGiftOrderDetail = new OrderDetail();
				storeOrderDetails.add(addGiftOrderDetail);

				//					addGiftOrderDetail.setStatus(addOrderObj.getStatus());

				addGiftOrderDetail.setIsGift(1);//是赠品
				addGiftOrderDetail.setoActivId(oActivAvlGiftProductVo.getActivId());
				//					addGiftOrderDetail.setUserId(_login_user_id);
				addGiftOrderDetail.setBrandId(oActivAvlGiftProductVo.getBrandId() == null ? null : oActivAvlGiftProductVo.getBrandId().intValue());
				addGiftOrderDetail.setBrandName(oActivAvlGiftProductVo.getBrandName());
				addGiftOrderDetail.setGoodId(oActivAvlGiftProductVo.getGoodsId());
				addGiftOrderDetail.setGoodName(oActivAvlGiftProductVo.getGoodsName());
				addGiftOrderDetail.setProductId(oActivAvlGiftProductVo.getProductId());
				addGiftOrderDetail.setSpecName(oActivAvlGiftProductVo.getSpecName());
				addGiftOrderDetail.setNavigateImg1(oActivAvlGiftProductVo.getThumbnail());
				addGiftOrderDetail.setStoreId((int) oActivAvlGiftProductVo.getStoreId());
				addGiftOrderDetail.setInventoryId(oActivAvlGiftProductVo.getInventoryId());
				addGiftOrderDetail.setProductPrice((int) oActivAvlGiftProductVo.getProductPrice());
				addGiftOrderDetail.setSalePrice((int) oActivAvlGiftProductVo.getSalePrice());
				addGiftOrderDetail.setSettlementPrice((int) oActivAvlGiftProductVo.getSettlementPrice());
				addGiftOrderDetail.setQuantity((int) oActivAvlGiftProductVo.getQuantity());
				//					addGiftOrderDetail.setBalancePaid(0);
				//					addGiftOrderDetail.setCashCoin(0);
				addGiftOrderDetail.setPromotionDiscount(0);
				//					addGiftOrderDetail.setTalentSerialId(0);
				//					addGiftOrderDetail.setTalentShareGoodId(0);
				//					addGiftOrderDetail.setTalentId(0);
				//					addGiftOrderDetail.setDiscount(0);
				//					addGiftOrderDetail.setTalentAgio(0);
				//					addGiftOrderDetail.setApplywelfareId(0);
				//					addGiftOrderDetail.setCreateTime(createTime);
				//					addGiftOrderDetail.setUpdateTime(updateTime);

				//					addGiftOrderDetail.setRefund(refund);
				//					addGiftOrderDetail.setCommentStatus(commentStatus);
				addGiftOrderDetail.setGoodsType(oActivAvlGiftProductVo.getGoodsType());
				//					addGiftOrderDetail.setRecommendFrom(recommendFrom);
				//					addGiftOrderDetail.setMemberRecommend(memberRecommend);
				//					addGiftOrderDetail.setOrderChannel(orderChannel);
				//					addGiftOrderDetail.setActivityType(activityType);
				//					addGiftOrderDetail.setTalentTeacher(talentTeacher);

				addGiftOrderDetail.setoActivDiscountFee(0l);

				addGiftOrderDetail.setTotalPrice(addGiftOrderDetail.getSalePrice().intValue() * addGiftOrderDetail.getQuantity());
				addGiftOrderDetail.setTotalSettlementprice(addGiftOrderDetail.getSettlementPrice().intValue() * addGiftOrderDetail.getQuantity());
				addGiftOrderDetail.setTotalFee((int) (addGiftOrderDetail.getTotalPrice().intValue() - addGiftOrderDetail.getPromotionDiscount() - addGiftOrderDetail.getoActivDiscountFee()));
			}
			orderActivInfoVo.getGiftProducts().remove(gifts.get(0).getStoreId());
		}
		return storeOrderDetails;
	}

	/** 验证海外购信息 */
	public ResponseResultModel<RespAddOrderInfo> overseaGoodsInfo(ResponseResultModel<RespAddOrderInfo> resultModel, RequestOrderDetail reqOrderDetail) {
		List<OrderDetail> _req_order_detail_list = reqOrderDetail.getOrderDetailList();
		GoodsExtends goodsExtends = null;
		for (OrderDetail orderDetail : _req_order_detail_list) {
			GoodsExtends tgoodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(orderDetail.getGoodId());
			if (tgoodsExtends != null && tgoodsExtends.getOverseasGoods() == 1) {// 是海外购
				goodsExtends=tgoodsExtends;
				break;
			}
		}
		if(goodsExtends!=null) {//是海外购商品
			RespAddOrderInfo  respAddOrderInfo= resultModel.getData();
			if(respAddOrderInfo!=null&&StringUtils.isNotBlank(respAddOrderInfo.getErrorMsg().getDesPriceChanger())) {//价格变动
			resultModel.setCodeAndMessage(20430,respAddOrderInfo.getErrorMsg().getDesPriceChanger());
			return resultModel;
		}
		if(respAddOrderInfo!=null&&respAddOrderInfo.getErrorMsg().getInvalidGoods()!=null&&respAddOrderInfo.getErrorMsg().getInvalidGoods().size()>0) {//失效商品
			resultModel.setCodeAndMessage(20430,respAddOrderInfo.getErrorMsg().getInvalidGoods().get(0).getMsg());
			return resultModel;
		}
		if(respAddOrderInfo!=null&&respAddOrderInfo.getErrorMsg().getInvalidGifts()!=null&&respAddOrderInfo.getErrorMsg().getInvalidGifts().size()>0) {//失效赠品
			resultModel.setCodeAndMessage(20430,"赠品已失效");
			return resultModel;
		}
		}
		return resultModel;
	}
	/** 验证海外购信息 */
	protected ResponseResultModel<RespAddOrderInfo> validationOverseasGoods(RequestOrderDetail reqOrderDetail) throws PlatformException {
		ResponseResultModel<RespAddOrderInfo> resultModel = new ResponseResultModel<RespAddOrderInfo>(ErrorEnum.C10000, new RespAddOrderInfo());
		List<OrderDetail> _req_order_detail_list = reqOrderDetail.getOrderDetailList();
		int OrderDetailSize = _req_order_detail_list.size();
		GoodsExtends goodsExtends = null;
		for (OrderDetail orderDetail : _req_order_detail_list) {
			goodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(orderDetail.getGoodId());
			if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1 && OrderDetailSize > 1) {// 是海外购
				resultModel.setError(ErrorEnum.C20421);
				return resultModel;
			}
		}
		if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1) {// 是海外购产品 判断逻辑暂时写死
			if (reqOrderDetail.getCashCoin() > 0 || reqOrderDetail.getBalanceAmount() > 0) {// 不允许使用妆币余额
				resultModel.setError(ErrorEnum.C20422);
				return resultModel;
			}
			if (reqOrderDetail.getPromotionId() > 0) {// 不允许使用优惠券
				resultModel.setError(ErrorEnum.C20423);
				return resultModel;
			}
			if (reqOrderDetail.getRedPacket() != null) {// 不允许使用兔币
				resultModel.setError(ErrorEnum.C20424);
				return resultModel;
			}
			if (reqOrderDetail.getIsBill() != null && reqOrderDetail.getIsBill() > 0) {// 不允许开票
				resultModel.setError(ErrorEnum.C20425);
				return resultModel;
			}
			UserAddress userAddress = userAddressService.selectUserAddressById(reqOrderDetail.getMemberDeliveryAddressId());
			if (StringUtils.isBlank(userAddress.getIdNumber())) {
				resultModel.setError(ErrorEnum.C20426);
				return resultModel;
			}
		}
		return null;
	}

	/** 验证海外购信息 获取满减信息后 */
	protected ResponseResultModel<RespAddOrderInfo> validationOverseasGoods(OrderObject orderObject,RequestOrderDetail reqOrderDetail,RespAddOrderInfo respAddOrderInfo) throws PlatformException {
		ResponseResultModel<RespAddOrderInfo> resultModel = new ResponseResultModel<RespAddOrderInfo>(ErrorEnum.C10000, new RespAddOrderInfo());
		List<OrderDetail> _req_order_detail_list = reqOrderDetail.getOrderDetailList();
		GoodsExtends goodsExtends = null;
		for (OrderDetail orderDetail : _req_order_detail_list) {
			goodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(orderDetail.getGoodId());
			if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1) {// 是海外购
				break;
			}
		}
		if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1) {// 是海外购产品 判断逻辑暂时写死
			if (orderObject.getoActivDiscountFee() != null && orderObject.getoActivDiscountFee() > 0) {// 不允许参与满减满赠
				resultModel.setError(ErrorEnum.C20427);
				return resultModel;
			}
			/*if(respAddOrderInfo!=null&&StringUtils.isNotBlank(respAddOrderInfo.getErrorMsg().getDesPriceChanger())) {//价格变动
				resultModel.setCodeAndMessage(20430,respAddOrderInfo.getErrorMsg().getDesPriceChanger());
				return resultModel;
			}
			if(respAddOrderInfo!=null&&respAddOrderInfo.getErrorMsg().getInvalidGoods()!=null&&respAddOrderInfo.getErrorMsg().getInvalidGoods().size()>0) {//失效商品
				resultModel.setCodeAndMessage(20430,respAddOrderInfo.getErrorMsg().getInvalidGoods().get(0).getMsg());
				return resultModel;
			}
			if(respAddOrderInfo!=null&&respAddOrderInfo.getErrorMsg().getInvalidGifts()!=null&&respAddOrderInfo.getErrorMsg().getInvalidGifts().size()>0) {//失效赠品
				resultModel.setCodeAndMessage(20430,"赠品已失效");
				return resultModel;
			}*/
		}
		return null;
	}

	@Override
	public ResponseResultModel<?> getAvlRedPacketList(RequestGetOrderObject requestGetOrderObject) {
		return new ResponseResultModel<List<UserRedPacketVo>>(ErrorEnum.C10000, new LinkedList<>());
	}

	@Override
	public boolean isFirstOrder(Long userId) {
		return false;
	}
	/**
	 * 封装消息体
	 **/
	protected Message createMessageProperties(String MessageID,String body) {
		MessageProperties MessageProperties = MessagePropertiesBuilder.newInstance().build();
		MessageProperties.setAppId(APPID);
		MessageProperties.setContentType(ContentType.APPLICATION_JSON.getMimeType());
		MessageProperties.setContentEncoding(ContentType.APPLICATION_JSON.getCharset().name());
		MessageProperties.setContentLength(body.length());
		MessageProperties.setMessageId(MessageID);
		MessageProperties.setHeader("serverIP", NetworkUtil.getLocalIP());
		return MessageBuilder.withBody(body.getBytes()).andProperties(MessageProperties).build();
	}
}
